import logging
from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from app.routes.analyze import router as analyze_router
from app.utils.helpers import setup_logging

setup_logging()
logger = logging.getLogger("lab_analyzer")


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Clean startup/shutdown logging (avoids confusing CancelledError noise)."""
    logger.info("Server started — POST /analyze ready")
    yield
    logger.info("Server shutting down (normal if you pressed Ctrl+C)")


app = FastAPI(
    title="Medical Lab Report Analyzer",
    description=(
        "AI-powered lab report OCR and analysis. "
        "Educational interpretations only — not medical advice."
    ),
    version="1.0.0",
    lifespan=lifespan,
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(analyze_router, tags=["Analysis"])


@app.get("/")
async def root():
    return {
        "service": "Medical Lab Report Analyzer",
        "docs": "/docs",
        "analyze_endpoint": "POST /analyze",
    }


@app.get("/health")
async def health():
    return {"status": "ok"}
