# app.py
from fastapi import FastAPI, Request
import uvicorn
import os
from contextlib import asynccontextmanager

# 导入配置
from config.settings import settings
# 导入数据库相关
from data.session import init_database, close_database_connections, close_async_database_connections
# 导入路由注册函数
from routes import register_routers
# 导入中间件注册函数
from middlewares import register_middlewares
# 导入日志工具
from utils.logger import get_logger

# 设置日志
logger = get_logger("app")

@asynccontextmanager
async def lifespan(app: FastAPI):
    """
    应用程序生命周期管理
    启动时初始化数据库和任务调度器，关闭时清理资源
    """
    # 启动前的初始化操作
    # 初始化数据库
    init_database()    
    # 启动增强版任务调度器
    from services.enhanced_scheduler import scheduler
    await scheduler.start(worker_count=settings.TASK_SCHEDULER_MIN_WORKER_COUNT)
    logger.info(f"增强版任务调度器已启动，最小工作线程数: {settings.TASK_SCHEDULER_MIN_WORKER_COUNT}，最大工作线程数: {settings.TASK_SCHEDULER_MAX_WORKER_COUNT}")
    
    yield
    
    # 应用程序关闭前的清理操作
    logger.info("应用程序关闭中...")
    
    # 停止增强版任务调度器
    from services.enhanced_scheduler import scheduler
    await scheduler.stop()
    logger.info("增强版任务调度器已停止")
    
    await close_async_database_connections()  # 关闭异步数据库连接
    close_database_connections()  # 关闭同步数据库连接

# 创建FastAPI应用
app = FastAPI(
    title=settings.APP_NAME,
    description=settings.APP_DESCRIPTION,
    version=settings.APP_VERSION,
    lifespan=lifespan,
    debug=settings.DEBUG
)
# 注册中间件
register_middlewares(app)
# 注册所有路由
register_routers(app)

# 主函数
if __name__ == "__main__":
    # 从环境变量中获取端口，默认为8000
    import time
    # start_time = time.time()
    port = int(os.environ.get("PORT", settings.SERVER_PORT))
    
    # 打印启动配置信息
    logger.info(f"服务器配置 - Host: 0.0.0.0, Port: {port}, Workers: {settings.SERVER_WORKERS}, Reload: {settings.SERVER_RELOAD}")
    end_time = time.time()
    # 启动服务器
    uvicorn.run(
        "app:app",
        host="0.0.0.0",
        port=port,
        reload=settings.SERVER_RELOAD,  # 使用SERVER_RELOAD而不是DEBUG
        workers=settings.SERVER_WORKERS
    )
