from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware

from app.config.settings import settings
from app.models.database import engine, Base
from app.routes import user, api_key, algorithm, openai, gateway, services, data_management, monitoring, permissions, history, deployment, gitea, repositories

# 创建数据库表
Base.metadata.create_all(bind=engine)

# 创建FastAPI应用
app = FastAPI(
    title=settings.APP_NAME,
    version=settings.APP_VERSION,
    description="智能算法展示平台API",
    docs_url="/docs",
    redoc_url="/redoc",
    # 设置更大的上传限制
    max_form_data_parts=50000,  # 允许最多50000个表单数据部分（包括文件）
    # 额外配置以绕过Starlette的默认限制
)

# 手动配置Starlette的表单解析器限制
from starlette.formparsers import MultiPartParser
MultiPartParser.max_files = 50000
MultiPartParser.max_fields = 50000

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

# 注册路由
app.include_router(user.router, prefix=settings.API_V1_STR)
app.include_router(api_key.router, prefix=settings.API_V1_STR)
app.include_router(algorithm.router, prefix=settings.API_V1_STR)
app.include_router(openai.router, prefix=settings.API_V1_STR)
app.include_router(gateway.router, prefix=settings.API_V1_STR)
app.include_router(services.router, prefix=settings.API_V1_STR)
app.include_router(data_management.router, prefix=settings.API_V1_STR)
app.include_router(monitoring.router, prefix=settings.API_V1_STR)
app.include_router(permissions.router, prefix=settings.API_V1_STR)
app.include_router(history.router, prefix=settings.API_V1_STR)
app.include_router(deployment.router)
app.include_router(gitea.router, prefix=settings.API_V1_STR)
app.include_router(repositories.router, prefix=settings.API_V1_STR)


@app.get("/")
async def root():
    """根路径"""
    return {
        "message": "Welcome to 智能算法展示平台 API",
        "version": settings.APP_VERSION,
        "docs": "/docs"
    }


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


@app.get("/@vite/client")
async def serve_vite_client():
    """处理 @vite/client 请求，避免 404 错误"""
    from fastapi.responses import Response
    return Response("", media_type="application/javascript")
