import os
import json
import logging
from datetime import datetime
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.staticfiles import StaticFiles

# 导入 configuration
from src.config.settings import (
    ALLOWED_ORIGINS, 
    DEV_ALLOWED_ORIGINS,
    ALLOW_DEV_ORIGINS, 
    UPLOAD_DIR,
    DATA_DIR,
    STORAGE_TYPE,
    NODE_ENV,
    REDIS_ENABLED,
    TRACING_ENABLED,
    OTLP_ENDPOINT
)
from src.config.database import init_db, engine
# 导入所有实体模型，确保 SQLModel.metadata 包含所有表
from src.models.entities import UserDB, UserApiKeyDB, ProjectDB, AssetDB, EpisodeDB, StoryboardDB, TaskDB, CanvasDB, CanvasMetadataDB
from src.models.session import UserSessionDB
from src.models.prompt_template import PromptTemplate, PromptTemplateFavorite
from src.utils.service_loader import load_services_from_config
from src.utils.logging import setup_logging
from src.admin_config import setup_admin

# 初始化 logging system
log_level = "DEBUG" if NODE_ENV == "development" else "INFO"
setup_logging(level=log_level, use_json=True)

logger = logging.getLogger(__name__)
logger.info(f"Starting Pixel API in {NODE_ENV} mode")

# 初始化 and Register Models
# Load from configuration directory
services_config_path = os.path.join(os.path.dirname(__file__), "config", "services")
load_services_from_config(services_config_path)

from src.api import config, projects, generations, storage, chat, canvas, canvas_metadata, tasks, health, skills, user_api_keys, auth, admin, audit_logs, storage_admin, prompt_templates
from src.middlewares.error_handler import setup_error_handler
from src.middlewares.request_tracking import setup_request_tracking
from src.middlewares.response_formatter import setup_response_formatter
from src.middlewares.metrics import (
    setup_metrics_middleware,
    set_application_info,
    get_metrics,
    get_metrics_content_type
)
from src.middlewares.tracing import setup_tracing, shutdown_tracing
from src.middlewares.rate_limiter import (
    setup_rate_limiter,
    init_rate_limiter,
    shutdown_rate_limiter
)
from src.middlewares.security import (
    setup_security_middleware,
    setup_security_headers_middleware,
    init_security_monitor,
    shutdown_security_monitor
)
from src.middlewares.performance import setup_performance_monitoring

# 验证 default model configuration
from src.services.provider.registry import ModelRegistry, ModelType

try:
    # Load user config to check defaults
    user_config_path = os.path.join(os.path.dirname(__file__), "config", "user_config.json")
    if os.path.exists(user_config_path):
        with open(user_config_path, 'r', encoding='utf-8') as f:
            user_config = json.load(f)
            
        # 验证 each default model
        model_mappings = {
            'defaultImageModel': ModelType.IMAGE,
            'defaultVideoModel': ModelType.VIDEO,
            'defaultAudioModel': ModelType.AUDIO,
            'defaultLyricsModel': ModelType.LYRICS,
            'defaultMusicModel': ModelType.MUSIC,
            'defaultLLMModel': ModelType.LLM
        }
        
        for config_key, model_type in model_mappings.items():
            default_id = user_config.get(config_key)
            if default_id:
                model_config = ModelRegistry.get_config(default_id)
                if not model_config:
                    logger.warning(
                        f"⚠️  Configured {config_key} '{default_id}' not found in registry. "
                        f"Please check your config/services/*.json files."
                    )
                else:
                    logger.info(f"✓ Default {model_type.value} model: {default_id}")
except Exception as e:
    logger.error(f"Failed to validate default models: {e}")

from fastapi.routing import APIRoute

def custom_generate_unique_id(route: APIRoute):
    return route.name

@asynccontextmanager
async def lifespan(app: FastAPI):
    """Lifespan context manager for startup and shutdown events"""
    # 导入 Unified Task Manager
    from src.services.task_manager import task_manager

    # 启动up
    logger.info("Application startup")

    # 初始化 database
    init_db()

    # 集合 application info for metrics
    set_application_info(version="0.1.0", environment=NODE_ENV)

    # 初始化 cache service if Redis is enabled
    if REDIS_ENABLED:
        from src.services.cache_service import get_cache_service
        cache = get_cache_service()
        await cache.connect()

        # 初始化 rate limiter
        await init_rate_limiter()

        # 初始化 security monitor
        await init_security_monitor()

    # 启动 Unified Task Manager
    await task_manager.start()
    logger.info("✓ Unified Task Manager started")

    # 清理up stuck projects
    from src.services.project_service import project_manager
    project_manager.cleanup_stuck_projects()
    
    yield
    
    # Shutdown
    logger.info("Application shutdown")
    
    # 停止 Unified Task Manager
    await task_manager.stop()
    logger.info("✓ Unified Task Manager stopped")
    
    # Shutdown tracing
    if TRACING_ENABLED:
        shutdown_tracing()
    
    # Disconnect cache service and rate limiter
    if REDIS_ENABLED:
        from src.services.cache_service import get_cache_service
        cache = get_cache_service()
        await cache.disconnect()
        
        # Shutdown rate limiter
        await shutdown_rate_limiter()
        
        # Shutdown security monitor
        await shutdown_security_monitor()

# 初始化 FastAPI app
app = FastAPI(
    title="Pixel API",
    description="""
    # Pixel - AI视频创作平台 API
    
    Pixel是一个智能平台，利用AI从剧本创作漫画和视频。
    
    ## 核心功能
    
    - **图片生成**: 支持多种AI模型生成高质量图片
    - **视频生成**: 从文本或图片生成视频内容
    - **剧本分析**: 智能分析剧本，提取角色、场景和道具
    - **项目管理**: 组织和管理创意项目
    - **Canvas编辑**: 可视化编辑分镜和资产
    - **任务管理**: 异步任务调度和状态跟踪
    
    ## 支持的AI提供商
    
    - **图片**: DashScope (Flux, Wanx), ModelScope (Kolors)
    - **视频**: Kling, Hailuo (MiniMax), ModelScope (CogVideoX, Wanx)
    - **文本**: DashScope (Qwen), Google (Gemini), VolcEngine (Doubao)
    
    ## API版本
    
    当前版本: v1  
    所有API端点使用 `/api/v1` 前缀
    
    ## 认证
    
    部分端点需要API密钥认证。请在请求头中包含:
    ```
    Authorization: Bearer YOUR_API_KEY
    ```
    
    ## 速率限制
    
    - 默认: 100 请求/分钟 (per IP)
    - 认证用户: 1000 请求/分钟
    
    ## 错误处理
    
    所有错误响应遵循统一格式:
    ```json
    {
      "code": "错误代码",
      "message": "错误描述",
      "details": {},
      "request_id": "请求ID",
      "timestamp": "时间戳"
    }
    ```
    
    ## 支持
    
    - 文档: [ARCHITECTURE.md](https://github.com/your-repo/ARCHITECTURE.md)
    - 问题反馈: [GitHub Issues](https://github.com/your-repo/issues)
    """,
    version="0.1.0",
    generate_unique_id_function=custom_generate_unique_id,
    lifespan=lifespan,
    openapi_tags=[
        {
            "name": "health",
            "description": "健康检查和系统状态"
        },
        {
            "name": "generations",
            "description": "AI生成服务 - 图片、视频、音频生成"
        },
        {
            "name": "tasks",
            "description": "任务管理 - 查询任务状态、取消任务"
        },
        {
            "name": "projects",
            "description": "项目管理 - 创建、查询、更新、删除项目"
        },
        {
            "name": "canvas",
            "description": "Canvas操作 - 节点和边的管理"
        },
        {
            "name": "canvas_metadata",
            "description": "Canvas元数据 - 保存和加载Canvas状态"
        },
        {
            "name": "storage",
            "description": "文件存储 - 上传和管理文件"
        },
        {
            "name": "config",
            "description": "配置管理 - 模型配置、用户设置"
        },
        {
            "name": "chat",
            "description": "聊天服务 - AI对话和剧本分析"
        },
    ],
    docs_url="/docs",
    redoc_url="/redoc",
    openapi_url="/openapi.json",
    contact={
        "name": "Pixel Team",
        "email": "support@pixel.ai"
    },
    license_info={
        "name": "MIT",
        "url": "https://opensource.org/licenses/MIT"
    }
)

# --- Middleware Setup ---
# 错误 handler middleware (must be first to catch all errors)
setup_error_handler(app)

# 请求 tracking middleware (adds request ID and logging)
setup_request_tracking(app)

# 响应 formatter middleware (adds metadata to responses)
setup_response_formatter(app)

# 安全 headers middleware (add security headers to all responses)
setup_security_headers_middleware(app)

# 安全 middleware (check for blocked IPs early)
setup_security_middleware(app)

# 比率 limiter middleware (before metrics to track rate-limited requests)
setup_rate_limiter(app)

# 性能 monitoring middleware
setup_performance_monitoring(app, slow_request_threshold=1.0)

# 指标 middleware
setup_metrics_middleware(app)

# Distributed tracing (must be setup before CORS)
setup_tracing(
    app,
    service_name="pixel-api",
    service_version="0.1.0",
    otlp_endpoint=OTLP_ENDPOINT,
    enabled=TRACING_ENABLED
)

# GZip compression middleware (compress responses > 1KB)
app.add_middleware(GZipMiddleware, minimum_size=1000)

app.add_middleware(
    CORSMiddleware,
    allow_origins=DEV_ALLOWED_ORIGINS if ALLOW_DEV_ORIGINS else ALLOWED_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# --- Static Files Setup ---
# Ensure upload directory exists
os.makedirs(UPLOAD_DIR, exist_ok=True)
app.mount("/uploads", StaticFiles(directory=UPLOAD_DIR), name="uploads")

# Mount data directory for local storage access
if STORAGE_TYPE == 'local':
    os.makedirs(DATA_DIR, exist_ok=True)
    app.mount("/files", StaticFiles(directory=DATA_DIR), name="files")

# --- Admin Interface Setup ---
setup_admin(app, engine)

# --- Include Routers ---
# Add /api/v1 prefix to all routers for API versioning
app.include_router(config.router, prefix="/api/v1", tags=["config"])
app.include_router(projects.router, prefix="/api/v1", tags=["projects"])
app.include_router(generations.router, prefix="/api/v1", tags=["generations"])
app.include_router(canvas.router, prefix="/api/v1", tags=["canvas"])
app.include_router(canvas_metadata.router, prefix="/api/v1", tags=["canvas-metadata"])
app.include_router(tasks.router, prefix="/api/v1", tags=["tasks"])
app.include_router(skills.router, prefix="/api/v1", tags=["skills"])
app.include_router(auth.router, prefix="/api/v1", tags=["auth"])
app.include_router(user_api_keys.router, prefix="/api/v1", tags=["user-api-keys"])
app.include_router(admin.router, prefix="/api/v1", tags=["admin"])
app.include_router(prompt_templates.router, prefix="/api/v1", tags=["prompt-templates"])
app.include_router(audit_logs.router, prefix="/api/v1", tags=["audit-logs"])
app.include_router(storage_admin.router, prefix="/api/v1", tags=["admin-storage"])

# 存储 and chat routers have their own prefixes, so we add /api/v1 before them
# This results in /api/v1/storage/* and /api/v1/chat/*
app.include_router(storage.router, prefix="/api/v1")
app.include_router(chat.router, prefix="/api/v1")

# 健康检查 routes (no prefix, used for k8s probes and monitoring)
app.include_router(health.router)

# Chat 同时挂载到根路径：兼容 OpenAI 客户端直连 /chat/completions（无 /api/v1 前缀）
# 与 /api/v1/chat/* 共用同一 router，仅路径不同
app.include_router(chat.router)

# --- API Endpoints ---
# 注意: Health check and metrics endpoints are now in health.py controller
