"""
ZIA FastAPI Application.

Mounts all routers, configures CORS and request logging middleware,
and sets up the lifespan context.
"""

from __future__ import annotations

from contextlib import asynccontextmanager
from typing import AsyncIterator

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

import zia
from zia.api.routers import agents, graph, health, telemetry, tenants

logger = structlog.get_logger("zia.api")


# Pre-load agent modules at import time so the registry is populated on first request.
# Must be at module level: Python 3.14 treats `import zia.*` inside a function as
# making `zia` a local name, causing UnboundLocalError for `zia.__version__`.
import zia.agents.risk_quant.agent    # noqa: F401
import zia.agents.supply_chain.agent  # noqa: F401
import zia.core.tools.builtins        # noqa: F401


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
    """Startup / shutdown hooks."""
    logger.info("zia.api.startup", version=zia.__version__)
    yield
    logger.info("zia.api.shutdown")


def create_app() -> FastAPI:
    app = FastAPI(
        title="ZIA — Zeron Universal Security Agent Platform",
        description=(
            "REST API for building, running, and governing cybersecurity agents. "
            "Authenticate via **X-API-Key** header."
        ),
        version=zia.__version__,
        contact={"name": "Zeron", "url": "https://zeron.one"},
        license_info={"name": "Proprietary"},
        lifespan=lifespan,
    )

    # ── CORS ─────────────────────────────────────────────────────────────────
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],   # tighten in production
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    # ── Request logging middleware ────────────────────────────────────────────
    @app.middleware("http")
    async def log_requests(request: Request, call_next):
        response = await call_next(request)
        logger.info(
            "http.request",
            method=request.method,
            path=request.url.path,
            status=response.status_code,
        )
        return response

    # ── Routers ───────────────────────────────────────────────────────────────
    app.include_router(health.router)
    app.include_router(tenants.router)
    app.include_router(agents.router)
    app.include_router(telemetry.router)
    app.include_router(graph.router)

    return app


app = create_app()
