"""
Nom du script : health.py
Chemin : /gitlab-bridge/app/api/v1/health.py
Description : Endpoint de santé applicative du bridge GitLab.
              Vérifie la connectivité à GitLab et retourne la version.
Options éventuelles : Aucune.
Exemples d'utilisation : GET /health.
Prérequis : Python 3.11+, FastAPI.
Auteur : Sylvain SCATTOLINI
Date de création / modification : 2026-04-09
Version : 1.2
"""

import logging

from fastapi import APIRouter
from fastapi.responses import JSONResponse

from app.clients.gitlab_client import GitLabClient
from app.core.exceptions import GitLabApiError

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

logger = logging.getLogger(__name__)


@router.get('/health')
def health() -> JSONResponse:
    """
    Vérifie que le bridge est opérationnel et que GitLab est joignable.
    Retourne HTTP 200 si tout est OK, HTTP 503 si GitLab est inaccessible.
    """
    client = GitLabClient()
    try:
        version_info = client.check_version()
        gitlab_version = version_info.get('version', 'unknown')
        return JSONResponse(
            status_code=200,
            content={
                'status': 'ok',
                'gitlab': 'reachable',
                'gitlab_version': gitlab_version,
            },
        )
    except GitLabApiError as exc:
        logger.warning("Health check : GitLab inaccessible — %s", exc)
        return JSONResponse(
            status_code=503,
            content={
                'status': 'degraded',
                'gitlab': 'unreachable',
                'detail': str(exc),
            },
        )
