import logging
from contextlib import asynccontextmanager

import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from config import settings
from db.session import engine

logging.basicConfig(
    level=getattr(logging, settings.LOG_LEVEL, logging.INFO),
    format="%(asctime)s [%(name)s] %(levelname)s: %(message)s",
)
logger = logging.getLogger("control-pipeline")


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Startup: verify DB and Qdrant connectivity."""
    logger.info("Control-Pipeline starting up ...")

    # Verify database connection
    try:
        with engine.connect() as conn:
            conn.execute(__import__("sqlalchemy").text("SELECT 1"))
        logger.info("Database connection OK")
    except Exception as exc:
        logger.error("Database connection failed: %s", exc)

    yield

    logger.info("Control-Pipeline shutting down ...")


app = FastAPI(
    title="BreakPilot Control Pipeline",
    description="Control generation, decomposition, and deduplication pipeline for the BreakPilot compliance platform.",
    version="1.0.0",
    lifespan=lifespan,
)

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

# Routers
from api import router as api_router  # noqa: E402

app.include_router(api_router)


# Health
@app.get("/health")
async def health():
    """Liveness probe."""
    db_ok = False
    try:
        with engine.connect() as conn:
            conn.execute(__import__("sqlalchemy").text("SELECT 1"))
        db_ok = True
    except Exception:
        pass

    status = "healthy" if db_ok else "degraded"
    return {
        "status": status,
        "service": "control-pipeline",
        "version": "1.0.0",
        "dependencies": {
            "postgres": "ok" if db_ok else "unavailable",
        },
    }


if __name__ == "__main__":
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=settings.PORT,
        reload=False,
        log_level="info",
    )
