from fastapi import FastAPI
from turbo_agent_auth.db import client
from loguru import logger
from time import perf_counter
from starlette.requests import Request
from turbo_agent_auth.api.routes import router as api_router
from turbo_agent_auth.logging import setup_logging
from turbo_agent_auth.services.auth_service import load_default_schemas

def create_app() -> FastAPI:
    app = FastAPI(title="turbo-agent-auth")

    # Core health endpoint
    @app.get("/health", summary="Health check")
    async def health():
        return {"status": "ok"}

    # Request logging middleware
    @app.middleware("http")
    async def _log_requests(request: Request, call_next):
        start = perf_counter()
        response = None
        try:
            response = await call_next(request)
            return response
        except Exception:
            logger.exception("Unhandled exception during request")
            raise
        finally:
            duration_ms = (perf_counter() - start) * 1000
            status = getattr(response, "status_code", 500)
            logger.bind(
                method=request.method,
                path=request.url.path,
                status=status,
                duration_ms=round(duration_ms, 2),
            ).info(f"{request.method} {request.url.path} -> {status} in {duration_ms:.2f}ms")

    # 启动/关闭事件：连接/断开数据库
    @app.on_event("startup")
    async def startup():
        # 配置日志
        setup_logging()
        # 加载默认 schema
        load_default_schemas()
        # 连接数据库
        logger.info("Connecting to database...")
        await client.connect()
        logger.info("Database connected.")    
    @app.on_event("shutdown")
    async def _shutdown():
        if client.is_connected():
            await client.disconnect()

    # API routes
    app.include_router(api_router)

    return app
