"""
柔性敏捷智能测试体系平台 - FastAPI 后端主入口
"""

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

from app.database import engine, Base
from app.api import intent_router, ai_router


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时创建数据库表
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)
    yield
    # 关闭时清理资源
    await engine.dispose()


app = FastAPI(
    title="柔性敏捷智能测试体系平台",
    description="Flexible Agile Intelligent Test System Platform API",
    version="1.0.0",
    lifespan=lifespan
)

# CORS 配置 - 允许 Electron 前端访问
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Electron 应用使用 file:// 协议
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(intent_router, prefix="/api")
app.include_router(ai_router, prefix="/api")


@app.get("/")
async def root():
    """根路径"""
    return {
        "name": "柔性敏捷智能测试体系平台",
        "version": "1.0.0",
        "status": "running"
    }


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


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "app.main:app",
        host="0.0.0.0",
        port=8080,
        reload=True
    )
