"""GET /health — liveness and readiness probe.

Verifies Firestore connectivity and GCS profiles bucket accessibility.
"""

from __future__ import annotations

import logging

from fastapi import APIRouter
from fastapi.responses import JSONResponse

_log = logging.getLogger(__name__)

router = APIRouter()

_GCS_PROFILES_BUCKET = "complyform-prod-profiles"


async def _check_gcs() -> bool:
    """Return ``True`` if the profiles bucket is accessible."""
    try:
        from google.cloud import storage

        client = storage.Client(project="complyform-prod")
        bucket = client.bucket(_GCS_PROFILES_BUCKET)
        return bucket.exists()
    except Exception:
        _log.exception("GCS health check failed")
        return False


@router.get("/health")
async def health() -> JSONResponse:
    """Health check endpoint for Cloud Run."""
    from backend.shared.firestore import check_firestore_health

    firestore_ok = await check_firestore_health()
    gcs_ok = await _check_gcs()

    checks = {
        "firestore": "ok" if firestore_ok else "fail",
        "gcs": "ok" if gcs_ok else "fail",
    }

    if firestore_ok and gcs_ok:
        return JSONResponse({"status": "ok", "checks": checks})

    return JSONResponse(
        {"status": "degraded", "checks": checks},
        status_code=503,
    )
