"""FastAPI application factory and entrypoint."""

from __future__ import annotations

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse

from legate import __version__
from legate.api import (
    agents,
    api_keys,
    approvals,
    audit,
    auth,
    billing,
    connectors,
    knowledge,
    members,
    runs,
    sso,
    workflows,
    workspaces,
)
from legate.billing.service import BillingLimitError
from legate.config import check_production_safety, get_settings
from legate.observability import metrics
from legate.observability.logging import configure_logging
from legate.observability.tracing import setup_tracing
from legate.security.ratelimit import RateLimitError


def create_app() -> FastAPI:
    configure_logging()
    settings = get_settings()
    # Fail fast rather than serve traffic with insecure production defaults.
    check_production_safety(settings)

    app = FastAPI(
        title="Legate Agent API",
        version=__version__,
        description="Self-hosted AI agent and workflow automation platform.",
    )

    app.add_middleware(
        CORSMiddleware,
        allow_origins=settings.cors_origin_list,
        allow_credentials=False,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    if settings.metrics_enabled:
        app.middleware("http")(metrics.metrics_middleware)

    setup_tracing(app)

    @app.exception_handler(BillingLimitError)
    async def _billing_limit(_: Request, exc: BillingLimitError) -> JSONResponse:
        # 402 Payment Required — a plan limit was hit.
        return JSONResponse(status_code=402, content={"detail": str(exc)})

    @app.exception_handler(RateLimitError)
    async def _rate_limited(_: Request, exc: RateLimitError) -> JSONResponse:
        return JSONResponse(status_code=429, content={"detail": str(exc)})

    @app.get("/health", tags=["system"])
    def health() -> dict[str, str]:
        """Liveness probe used by Docker, CI, and load balancers."""
        return {"status": "ok", "version": __version__, "env": settings.legate_env}

    if settings.metrics_enabled:

        @app.get("/metrics", tags=["system"])
        def metrics_route():
            """Prometheus scrape endpoint."""
            return metrics.metrics_endpoint()

    app.include_router(auth.router)
    app.include_router(workspaces.router)
    app.include_router(members.router)
    app.include_router(api_keys.router)
    app.include_router(audit.router)
    app.include_router(agents.router)
    app.include_router(runs.router)
    app.include_router(knowledge.router)
    app.include_router(connectors.router)
    app.include_router(approvals.router)
    app.include_router(workflows.router)
    app.include_router(billing.router)
    app.include_router(sso.router)

    return app


app = create_app()
