"""
AI Interview Backend - FastAPI 应用入口
"""
import os
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from loguru import logger

from app.config import settings
from app.routers import candidate, room, chat, init, files, admin

# 创建 FastAPI 应用
app = FastAPI(
    title="AI Interview API",
    description="AI 语音面试系统后端 API",
    version="0.1.0",
    docs_url="/docs" if settings.DEBUG else None,
    redoc_url="/redoc" if settings.DEBUG else None,
)

# 配置 CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由（用户端）
app.include_router(candidate.router, prefix="/api", tags=["候选人"])
app.include_router(room.router, prefix="/api", tags=["房间"])
app.include_router(chat.router, prefix="/api", tags=["对话"])
app.include_router(init.router, prefix="/api", tags=["初始化"])
app.include_router(files.router, prefix="/api", tags=["文件"])

# 管理后台路由
app.include_router(admin.router, tags=["管理后台"])


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


@app.on_event("startup")
async def startup_event():
    """应用启动事件"""
    logger.info("AI Interview Backend starting...")
    logger.info(f"Debug mode: {settings.DEBUG}")
    logger.info(f"Coze Bot ID: {settings.COZE_BOT_ID}")
    logger.info(f"Tunnel URL: {settings.TUNNEL_URL or settings.NGROK_URL}")
    
    # 创建上传目录
    os.makedirs(settings.UPLOAD_DIR, exist_ok=True)
    logger.info(f"Upload directory: {settings.UPLOAD_DIR}")


@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭事件"""
    logger.info("AI Interview Backend shutting down...")


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=settings.API_PORT,
        reload=settings.DEBUG,
    )
