"""FastAPI 应用入口"""
from contextlib import asynccontextmanager
import os
import sys
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from app.config import settings
from app.api import router as api_router
from app.core.exceptions import register_exception_handlers
from app.core.redis import RedisService


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时初始化
    await RedisService.init()
    yield
    # 关闭时清理
    await RedisService.close()


def create_app() -> FastAPI:
    """创建FastAPI应用实例"""
    app = FastAPI(
        title=settings.APP_NAME,
        version=settings.APP_VERSION,
        description="Dify插件服务API",
        openapi_url=f"{settings.API_V1_PREFIX}/openapi.json",
        docs_url="/docs",
        redoc_url="/redoc",
        lifespan=lifespan,
        servers=[
            {"url": f"http://{settings.API_HOST}:{settings.PORT}", "description": "API服务器"},
        ],
    )
    
    # 注册CORS中间件
    app.add_middleware(
        CORSMiddleware,
        allow_origins=settings.CORS_ORIGINS,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    
    # 注册异常处理器
    register_exception_handlers(app)
    
    # 注册路由
    app.include_router(api_router, prefix=settings.API_V1_PREFIX)
    
    return app


app = create_app()


def print_routes(app: FastAPI):
    """打印所有注册的路由"""
    print("\n" + "=" * 60)
    print("Registered Routes:")
    print("=" * 60)
    for route in app.routes:
        if hasattr(route, "methods"):
            methods = ", ".join(route.methods - {"HEAD", "OPTIONS"})
            print(f"  {methods:8} {route.path}")
    print("=" * 60 + "\n")


# 启动时打印路由
print_routes(app)


@app.get("/health", tags=["健康检查"], summary="健康检查接口")
async def health_check():
    """服务健康检查"""

