"""``citadel status`` — health check for a Citadel installation."""

from __future__ import annotations

import sys

from kubernetes import client, config
from kubernetes.client.rest import ApiException


def _load_kube_config() -> None:
    try:
        config.load_incluster_config()
    except config.ConfigException:
        config.load_kube_config()


def _check(description: str, ok: bool) -> bool:
    mark = "ok" if ok else "FAIL"
    print(f"  [{mark:>4}]  {description}", file=sys.stderr)
    return ok


def status(namespace: str = "citadel-system") -> bool:
    """Check Citadel installation health.  Returns True if all checks pass."""
    _load_kube_config()

    core = client.CoreV1Api()
    apps = client.AppsV1Api()
    ext = client.ApiextensionsV1Api()

    checks: list[bool] = []

    # 1. Namespace exists
    try:
        core.read_namespace(namespace)
        checks.append(_check(f"Namespace {namespace} exists", True))
    except ApiException:
        checks.append(_check(f"Namespace {namespace} exists", False))

    # 2. CRDs registered
    crd_names = (
        "nodeterminationpolicies.citadel.dev",
        "namespaceinfrastructures.citadel.dev",
    )
    for crd_name in crd_names:
        try:
            ext.read_custom_resource_definition(crd_name)
            checks.append(_check(f"CRD {crd_name}", True))
        except ApiException:
            checks.append(_check(f"CRD {crd_name}", False))

    # 3. Deployment exists and has available replicas
    try:
        dep = apps.read_namespaced_deployment("citadel-operator", namespace)
        available = dep.status.available_replicas or 0
        checks.append(_check(f"Deployment citadel-operator ({available} available)", available >= 1))
    except ApiException:
        checks.append(_check("Deployment citadel-operator", False))

    # 4. Operator pod Running and Ready
    try:
        pods = core.list_namespaced_pod(
            namespace,
            label_selector="app.kubernetes.io/name=citadel-operator",
        )
        if pods.items:
            pod = pods.items[0]
            phase = pod.status.phase
            ready = any(
                c.type == "Ready" and c.status == "True"
                for c in (pod.status.conditions or [])
            )
            checks.append(_check(f"Pod {pod.metadata.name} ({phase}, ready={ready})", ready))
        else:
            checks.append(_check("Operator pod exists", False))
    except ApiException:
        checks.append(_check("Operator pod exists", False))

    # Summary
    passed = sum(checks)
    total = len(checks)
    print(f"\n  {passed}/{total} checks passed", file=sys.stderr)

    return all(checks)
