"""Health and release status endpoints."""

from __future__ import annotations

from typing import Annotated

from fastapi import APIRouter, Depends

from ilum.api.auth import require_auth
from ilum.api.deps import get_manager
from ilum.api.models import (
    HealthResponse,
    PodStatusResponse,
    ReleaseResponse,
)
from ilum.core.release import ReleaseManager

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


@router.get("/health", response_model=HealthResponse)
async def health() -> HealthResponse:
    """Liveness/readiness probe — always returns 200."""
    import os

    from ilum.api.deps import _manager

    if _manager is not None:
        return HealthResponse(
            status="ok",
            release=os.environ.get("ILUM_RELEASE_NAME", "ilum"),
            namespace=_manager.helm.namespace,
        )
    return HealthResponse(status="ok")


@router.get("/release", response_model=ReleaseResponse, dependencies=[Depends(require_auth)])
async def get_release(
    mgr: Annotated[ReleaseManager, Depends(get_manager)],
) -> ReleaseResponse:
    """Return info about the connected Helm release."""
    import os

    release_name = os.environ.get("ILUM_RELEASE_NAME", "ilum")
    info = mgr.get_release_info(release_name)
    return ReleaseResponse(
        name=info.name,
        namespace=info.namespace,
        status=info.status,
        chart=info.chart,
        chart_version=info.chart_version,
        revision=info.revision,
        last_deployed=info.last_deployed,
    )


@router.get("/pods", response_model=list[PodStatusResponse], dependencies=[Depends(require_auth)])
async def list_pods(
    mgr: Annotated[ReleaseManager, Depends(get_manager)],
) -> list[PodStatusResponse]:
    """Return all pods in the release namespace."""
    import os

    namespace = os.environ.get("ILUM_NAMESPACE", mgr.helm.namespace)
    pods = mgr.k8s.list_pods(namespace)
    return [
        PodStatusResponse(
            name=p.name,
            namespace=p.namespace,
            phase=p.phase,
            ready=p.ready,
            restart_count=p.restart_count,
            containers=list(p.containers),
        )
        for p in pods
    ]
