from fastapi import APIRouter, status
from fastapi.responses import JSONResponse

from app.core.database import is_db_ready
from app.core.env import env_str

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


@router.get("/health")
async def health():
    mongo_ok = await is_db_ready()
    app_status = "ok" if mongo_ok else "degraded"
    return {
        "status": app_status,
        "checks": {
            "mongo": "up" if mongo_ok else "down",
        },
        "service": {
            "name": env_str("APP_NAME", "Repo Docs Ingestion Service"),
            "version": env_str("SERVICE_VERSION", "1.0.0"),
            "env": env_str("ENV", "production"),
        },
    }


@router.get("/ready")
async def ready():
    mongo_ok = await is_db_ready()
    payload = {
        "status": "ready" if mongo_ok else "not_ready",
        "checks": {
            "mongo": "up" if mongo_ok else "down",
        },
    }
    if not mongo_ok:
        return JSONResponse(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, content=payload)
    return payload


@router.get("/version")
async def version():

    return {
        "name": env_str("APP_NAME", "Repo Docs Ingestion Service"),
        "version": env_str("SERVICE_VERSION", "1.0.0"),
        "env": env_str("ENV", "production"),
    }