from fastapi import APIRouter, FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException

from app.api.endpoints import auth, users
from app.core.config import settings
from app.utils.response import error_response

# 创建FastAPI应用
app = FastAPI(
    title=settings.PROJECT_NAME,
    openapi_url=f"{settings.API_V1_STR}/openapi.json",
    docs_url="/api-docs",
    redoc_url="/redoc",
)

# 配置CORS
if settings.BACKEND_CORS_ORIGINS:
    app.add_middleware(
        CORSMiddleware,
        allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
else:
    # 默认CORS配置
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

# 创建API路由
api_router = APIRouter()

# 添加各个端点路由
api_router.include_router(auth.router, prefix="/auth", tags=["认证"])
api_router.include_router(users.router, prefix="/users", tags=["用户"])

# 将API路由添加到应用
app.include_router(api_router, prefix=settings.API_V1_STR)


# 自定义异常处理
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request, exc):
    return JSONResponse(
        status_code=exc.status_code,
        content=error_response(
            message=str(exc.detail),
            code=exc.status_code
        )
    )


@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
    errors = []
    for error in exc.errors():
        error_msg = f"{error['loc'][-1]}: {error['msg']}"
        errors.append(error_msg)
    
    return JSONResponse(
        status_code=400,
        content=error_response(
            message="请求参数验证失败",
            code=400,
            data={"errors": errors}
        )
    )


# 健康检查路由
@app.get("/health")
async def health_check():
    import platform
    import psutil
    from datetime import datetime
    
    return {
        "status": "OK",
        "timestamp": datetime.now().isoformat(),
        "uptime": psutil.boot_time(),
        "environment": settings.DEBUG and "development" or "production",
        "no_db_mode": settings.NO_DB_MODE,
        "system_info": {
            "python_version": platform.python_version(),
            "platform": platform.platform(),
            "cpu_count": psutil.cpu_count(),
            "memory": {
                "total": psutil.virtual_memory().total,
                "available": psutil.virtual_memory().available,
            }
        }
    }


# 系统统计路由
@app.get("/system-stats")
async def system_stats():
    import platform
    import psutil
    from datetime import datetime
    
    return {
        "status": "OK",
        "timestamp": datetime.now().isoformat(),
        "environment": settings.DEBUG and "development" or "production",
        "python_version": platform.python_version(),
        "memory_usage": dict(psutil.virtual_memory()._asdict()),
        "uptime": psutil.boot_time(),
        "cpu_count": psutil.cpu_count(),
        "platform": platform.platform(),
        "architecture": platform.architecture(),
        "no_db_mode": settings.NO_DB_MODE
    }