import logging
from contextlib import asynccontextmanager

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

from app.api.router import api_router
from app.core.config import settings
from app.services.pdf_cleanup import cleanup_expired_pdfs

logger = logging.getLogger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时执行
    logger.info("[应用启动] 初始化定时任务...")

    # 启动后台清理任务
    import asyncio
    async def cleanup_task():
        while True:
            try:
                # 每天执行一次PDF清理
                await asyncio.sleep(24 * 60 * 60)  # 24小时
                logger.info("[定时任务] 开始执行PDF清理...")
                cleanup_expired_pdfs()
            except Exception as e:
                logger.error(f"[定时任务] PDF清理失败: {str(e)}")

    # 启动后台任务
    asyncio.create_task(cleanup_task())
    logger.info("[应用启动] 定时任务已启动")

    yield

    # 关闭时执行
    logger.info("[应用关闭] 清理资源...")


def create_app() -> FastAPI:
    app = FastAPI(title=settings.app_name, lifespan=lifespan)
    app.add_middleware(
        CORSMiddleware,
        allow_origins=settings.cors_origins,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    app.include_router(api_router)
    return app


app = create_app()
