"""FastAPI application — Crystallise AI backend (NetReady MVP)."""

import logging
import os

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

from .auth_middleware import APIKeyAuthMiddleware
from .routers import (
    config,
    criteria,
    indexer,
    screening,
)

logger = logging.getLogger(__name__)


app = FastAPI(
    title="Crystallise AI Backend",
    version="0.1.0",
    description="Stateless AI services for systematic review screening and indexing.",
)

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

app.add_middleware(APIKeyAuthMiddleware)

# Versioned routes (canonical)
app.include_router(indexer.router, prefix="/v1/indexer", tags=["indexer"])
app.include_router(screening.router, prefix="/v1/screening", tags=["screening"])
app.include_router(criteria.router, prefix="/v1/criteria", tags=["criteria"])
app.include_router(config.router, prefix="/v1/config", tags=["config"])

# Unversioned aliases (backwards-compatible)
app.include_router(indexer.router, prefix="/indexer", tags=["indexer"])
app.include_router(screening.router, prefix="/screening", tags=["screening"])
app.include_router(criteria.router, prefix="/criteria", tags=["criteria"])
app.include_router(config.router, prefix="/config", tags=["config"])


@app.get("/health")
@app.get("/v1/health")
async def health():
    return {"status": "ok"}


@app.get("/health/ready")
@app.get("/v1/health/ready")
async def health_ready():
    """Readiness probe — checks DB connectivity and OpenAI key presence."""
    checks: dict[str, str] = {}
    overall = True

    # DB check
    try:
        from crystallise.db.backend import get_backend

        db = get_backend()
        with db.get_connection() as conn:
            db.execute(conn, "SELECT 1")
        checks["database"] = "ok"
    except Exception as e:
        checks["database"] = f"error: {e}"
        overall = False

    # OpenAI key check (presence only, not a live API call)
    api_key = os.environ.get("CRYSTALLISE_OPENAI_API_KEY") or os.environ.get("OPENAI_API_KEY")
    checks["openai_key"] = "configured" if api_key else "missing"
    if not api_key:
        overall = False

    status_code = 200 if overall else 503
    return JSONResponse(
        status_code=status_code,
        content={"status": "ready" if overall else "degraded", "checks": checks},
    )
