"""
Creative Studio - FastAPI 应用入口
基于 Agent + Skill 架构的 AI 剧集创作平台
"""
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
from app.config import settings
from app.utils.logger import get_logger

# 初始化日志
logger = get_logger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时执行
    logger.info(f"🚀 {settings.app_name} v{settings.app_version} 启动中...")
    logger.info(f"📝 环境: {settings.environment}")
    logger.info(f"🔧 调试模式: {settings.debug}")

    # 初始化 Skill 管理器
    from app.core.skills.skill_manager import get_skill_manager
    skill_manager = get_skill_manager()
    # 预热 Skill 缓存（异步加载所有 skills，避免首次请求阻塞）
    await skill_manager.warmup_cache()

    # 注册 Builtin Skills 的工具（Agent-Skill 生命周期：注册阶段）
    await skill_manager.register_builtin_tools()
    logger.info(f"✅ Builtin Skills 工具注册完成")

    # 初始化 GLM 客户端
    from app.core.llm.glm_client import get_glm_client
    glm_client = get_glm_client()
    logger.info(f"✅ GLM 客户端初始化完成，模型: {glm_client.model}")

    # 初始化剧集创作 Agent
    from app.core.agents.series_creation_agent import get_series_agent
    agent = get_series_agent()
    logger.info(f"✅ 剧集创作 Agent 初始化完成")

    # 初始化审核管理器
    from app.core.review.review_manager import get_review_manager
    from app.core.review.review_task_manager import get_review_task_manager
    review_mgr = get_review_manager()
    review_task_mgr = get_review_task_manager()
    logger.info(f"✅ 审核管理器初始化完成")
    logger.info(f"✅ 审核任务管理器初始化完成")

    # 初始化批量执行器
    from app.core.execution.batch_executor import get_batch_executor
    batch_exec = get_batch_executor()
    logger.info(f"✅ 批量执行器初始化完成")

    # 初始化重试管理器
    from app.core.execution.retry_manager import get_retry_manager
    retry_mgr = get_retry_manager()
    logger.info(f"✅ 重试管理器初始化完成")

    yield

    # 关闭时执行
    logger.info(f"👋 {settings.app_name} 正在关闭...")


# 创建 FastAPI 应用
app = FastAPI(
    title=settings.app_name,
    description="基于 Agent + Skill 架构的 AI 剧集创作平台",
    version=settings.app_version,
    lifespan=lifespan,
    docs_url="/docs",
    redoc_url="/redoc",
    openapi_url="/openapi.json"
)

# 配置 CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.cors_origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# ============================================
# 根路由
# ============================================
@app.get("/", tags=["根路径"])
async def root():
    """API 根路径"""
    return {
        "name": settings.app_name,
        "version": settings.app_version,
        "description": "基于 Agent + Skill 架构的 AI 剧集创作平台",
        "docs": "/docs",
        "status": "running"
    }


@app.get("/health", tags=["健康检查"])
async def health_check():
    """健康检查端点"""
    return {
        "status": "healthy",
        "environment": settings.environment
    }


# ============================================
# API 路由注册
# ============================================
from app.api.v1 import (
    skills, projects, ai_assistant, memory, review, review_task,
    review_cards, confirm_cards, websocket, uploads, episodes,
    async_tasks, ai_async, skills_async
)

app.include_router(skills.router, prefix="/api/v1")
app.include_router(skills_async.router, prefix="/api/v1")
app.include_router(projects.router, prefix="/api/v1")
app.include_router(episodes.router, prefix="/api/v1")
app.include_router(ai_assistant.router, prefix="/api/v1")
app.include_router(async_tasks.router, prefix="/api/v1")
app.include_router(ai_async.router, prefix="/api/v1")
app.include_router(memory.router, prefix="/api/v1")
app.include_router(review.router, prefix="/api/v1")
app.include_router(review_task.router, prefix="/api/v1")
app.include_router(review_cards.router, prefix="/api/v1")
app.include_router(confirm_cards.router, prefix="/api/v1")
app.include_router(uploads.router, prefix="/api/v1")
app.include_router(websocket.router)  # WebSocket router doesn't need prefix

logger.info("✅ API 路由注册完成")


# ============================================
# 启动说明
# ============================================
if __name__ == "__main__":
    import uvicorn

    uvicorn.run(
        "app.main:app",
        host=settings.host,
        port=settings.port,
        reload=settings.debug,
        log_level=settings.log_level.lower()
    )
