"""
FastAPI主程序入口
"""
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from backend.database import init_db
from backend.routers import students, rollcall, scores

# 创建FastAPI应用
app = FastAPI(title="课堂随机点名系统API", description="基于FastAPI的课堂随机点名系统后端API", version="1.0.0")

# 配置CORS（允许前端跨域访问）
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境应设置具体的前端地址
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(students.router)
app.include_router(rollcall.router)
app.include_router(scores.router)

@app.on_event("startup")
async def startup_event():
    """应用启动时初始化数据库"""
    try:
        init_db()
        print("数据库初始化成功")
    except Exception as e:
        print(f"数据库初始化失败: {e}")


@app.get("/")
def root():
    """根路径"""
    return {"message": "课堂随机点名系统API", "version": "1.0.0", "docs": "/docs"}


@app.get("/health")
def health_check():
    """健康检查"""
    return {"status": "ok"}


if __name__ == "__main__":
    import uvicorn
    from backend.config import API_HOST, API_PORT
    uvicorn.run(app, host=API_HOST, port=API_PORT)
