"""Rotas INFRA CODE — stack completo VMs 112/114/122/123/130."""

from __future__ import annotations

from fastapi import APIRouter, Depends, HTTPException

from app import auth, integration_health
from app.stack_health import run_stack_health

router = APIRouter(prefix="/api/v1/infra", tags=["infra-stack"])


def _can_stack(user: auth.DeskUser) -> bool:
    return user.role in ("super_admin", "devops", "developer")


@router.get("/stack/status")
def infra_stack_status(user: auth.DeskUser = Depends(auth.get_current_user)):
    if not _can_stack(user):
        raise HTTPException(403, "permissão insuficiente")
    data = run_stack_health()
    try:
        with auth.db() as conn:
            health = integration_health.build_health_report(conn)
        onboard = health.get("vm112_onboard") or {}
        vm_ok = onboard.get("vm112_api", {}).get("reachable")
        for vm in data["vms"]:
            if vm["vm"] != "122":
                continue
            for svc in vm["services"]:
                if svc["id"] == "vm122-webhook-soc":
                    svc["ok"] = health.get("status") in ("ok", "degraded") and vm_ok
                    svc["status"] = health.get("status") or "check"
                    gap = onboard.get("gap_minutes")
                    svc["detail"] = f"integração {health.get('status')} · gap {gap if gap is not None else '—'} min"
    except Exception:
        pass
    return data
