"""Liveness / readiness endpoints."""

from __future__ import annotations

from fastapi import APIRouter
from fastapi.responses import JSONResponse

from ocr_sprint import __version__
from ocr_sprint.config import get_settings
from ocr_sprint.pipeline import ocr as _ocr
from ocr_sprint.pipeline import table as _table

router = APIRouter(tags=["health"])


@router.get("/health")
async def health() -> dict[str, str]:
    """Lightweight liveness check — does NOT touch the OCR engine."""
    return {"status": "ok", "version": __version__}


@router.get("/health/ready")
async def readiness() -> JSONResponse:
    """Readiness check — returns 200 when OCR models are loaded, 503 if still warming up."""
    settings = get_settings()
    ocr_ready = _ocr._instance is not None
    table_ready = (not settings.tables_enabled) or _table._instance is not None
    ready = ocr_ready and table_ready
    payload = {
        "status": "ready" if ready else "warming_up",
        "version": __version__,
        "models": {
            "paddleocr": "ready" if ocr_ready else "loading",
            "pp_structure": (
                "disabled" if not settings.tables_enabled else "ready" if table_ready else "loading"
            ),
        },
    }
    return JSONResponse(content=payload, status_code=200 if ready else 503)
