"""FastAPI 主应用"""

import os
from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from .api import api_router
from .api import chat as chat_api
from .api import config as config_api
from .api import models as models_api
from .services.ai_service import AIService
from .services.chat_service import ChatService
from .services.config_service import ConfigService

# 全局服务实例
config_service: ConfigService = None
chat_service: ChatService = None
ai_service: AIService = None


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    global config_service, chat_service, ai_service

    # 启动时初始化服务
    print("🚀 初始化服务...")

    # 获取配置文件路径（从环境变量或当前目录）
    config_path = os.getenv("LUMI_CONFIG_PATH", "config.yaml")

    # 初始化配置服务
    config_service = ConfigService(config_path)
    config = config_service.get_config()

    # 初始化聊天服务
    chat_service = ChatService(
        history_file=config.chat.history_file, max_history=config.chat.max_history
    )

    # 初始化 AI 服务
    ai_service = AIService(config.providers)

    # 注入服务到 API 模块
    config_api.init_config_service(config_service)
    models_api.init_config_service(config_service)
    chat_api.init_services(config_service, chat_service, ai_service)

    print(f"✅ 服务初始化完成")
    print(f"📁 配置文件: {config_path}")
    print(f"🤖 已加载 {len(config.providers)} 个 AI 供应商")
    print(f"🎭 已加载 {len(config.live2d_models)} 个 Live2D 模型")

    yield

    # 关闭时清理资源
    print("👋 关闭服务...")


def create_app() -> FastAPI:
    """创建 FastAPI 应用"""
    app = FastAPI(
        title="LumiServer API",
        description="LumiDesktop AI + Live2D 虚拟桌宠后端服务",
        version="1.0.0",
        lifespan=lifespan,
    )

    # CORS 中间件（本地开发允许所有来源）
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    # 注册路由
    app.include_router(api_router)

    # 根路径
    @app.get("/")
    async def root():
        return {
            "name": "LumiServer",
            "version": "1.0.0",
            "docs": "/docs",
            "health": "/api/v1/system/health",
        }

    return app


# 创建应用实例
app = create_app()


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=52341, log_level="info")
