# Copyright (c) 2025, JINGROW and contributors
# For license information, please see license.txt

"""
Jingrow 应用入口
"""

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
from jingrow.utils.router_auto_register import include_routers_from_package
from jingrow.services.scheduler import start_scheduler, stop_scheduler
from jingrow.services.whitelist import router

@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动事件
    try:
        # 启动调度器
        await start_scheduler()
        print("调度器已启动")
        
        # 验证调度器状态
        from jingrow.services.scheduler import get_scheduler_status
        status = get_scheduler_status()
        print(f"调度器状态: 运行={status['running']}, 任务数={status['total_jobs']}")
        
    except Exception as e:
        print(f"启动调度器失败: {e}")
        import traceback
        traceback.print_exc()
    
    yield
    
    # 关闭事件
    try:
        await stop_scheduler()
        print("调度器已停止")
    except Exception as e:
        print(f"停止调度器失败: {e}")

def create_app():
    """创建FastAPI应用"""
    app = FastAPI(
        title="Jingrow",
        description="Jingrow Backend",
        version="1.0.0",
        lifespan=lifespan
    )
    
    # 添加CORS中间件
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    
    # 自动注册 Jingrow 框架的静态路由（无前缀）
    include_routers_from_package(app, "jingrow.api")
    
    # 手动注册动态路由（最后注册，避免冲突）
    app.include_router(router, prefix="/jingrow")
    
    return app

app = create_app()
