"""Health and status endpoints."""

from __future__ import annotations

from fastapi import APIRouter

from Project.Sanad.core.logger import get_logger

log = get_logger("health_route")

router = APIRouter()


def _safe_status(component, name: str) -> dict:
    """Get status without crashing the whole endpoint if one component fails."""
    if component is None:
        return {"available": False}
    try:
        if hasattr(component, "status") and callable(component.status):
            return component.status()
        return {"available": True}
    except Exception as exc:
        log.warning("status() failed for %s: %s", name, exc)
        return {"available": True, "error": str(exc)}


@router.get("/health")
async def health():
    from Project.Sanad.main import brain
    return {
        "status": "ok",
        "brain": _safe_status(brain, "brain"),
    }


@router.get("/status")
async def full_status():
    from Project.Sanad.main import (
        brain, arm, voice_client, macro_rec, macro_play,
        live_voice, live_sub, wake_mgr,
    )
    return {
        "brain":          _safe_status(brain, "brain"),
        "voice":          _safe_status(voice_client, "voice"),
        "arm":            _safe_status(arm, "arm"),
        "macro_recorder": _safe_status(macro_rec, "macro_rec"),
        "macro_player":   _safe_status(macro_play, "macro_play"),
        "live_voice":     _safe_status(live_voice, "live_voice"),
        "live_subprocess": _safe_status(live_sub, "live_sub"),
        "wake_manager":   _safe_status(wake_mgr, "wake_mgr"),
    }
