"""AIF Platform API — FastAPI entry (BFF over normbase + eda_agent)."""

from __future__ import annotations

from contextlib import asynccontextmanager

import httpx
from fastapi import APIRouter, FastAPI
from fastapi.middleware.cors import CORSMiddleware

from aif_platform.server.api import admin, agents, auth, field_keys, fields, health, keys, norms, orgs
from aif_platform.server.config import settings
from aif_platform.server.db.connection import close_db, init_db
from aif_platform.server.infra.upstream import EdaClient, NormbaseClient


@asynccontextmanager
async def lifespan(app: FastAPI):
    await init_db()
    timeout = httpx.Timeout(settings.http_client_timeout_seconds)
    client = httpx.AsyncClient(timeout=timeout)
    app.state.http_client = client
    app.state.normbase_client = NormbaseClient(client, settings.normbase_base_url)
    app.state.eda_client = EdaClient(client, settings.eda_base_url)
    yield
    await client.aclose()
    await close_db()


app = FastAPI(
    title="AIF Platform API",
    description="Agent Information Field — product BFF",
    version="0.1.0",
    lifespan=lifespan,
)

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

api = APIRouter(prefix="/api/v1")
api.include_router(auth.router)
api.include_router(orgs.router)
api.include_router(fields.router)
api.include_router(norms.router)
api.include_router(agents.router)
api.include_router(keys.router)
api.include_router(field_keys.router)
api.include_router(admin.router)
app.include_router(api)
app.include_router(health.router)


@app.get("/")
async def root():
    return {"name": "AIF Platform API", "version": "0.1.0", "status": "running"}


def main() -> None:
    import uvicorn

    uvicorn.run(
        "aif_platform.server.main:app",
        host=settings.api_host,
        port=settings.platform_api_port,
        factory=False,
    )
