#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Pipeline health CLI command: `pulse health`"""
import json

from pulse.cli import STATE_DIR

HEALTH_DIR = STATE_DIR / "health"


def _age_str(seconds: float) -> str:
    """Human-readable age string."""
    if seconds > 86400:
        return f"{seconds / 3600:.0f}h"
    if seconds > 3600:
        return f"{seconds / 3600:.1f}h"
    if seconds > 60:
        return f"{seconds / 60:.0f}min"
    return f"{seconds:.0f}s"


def cmd_health():
    """Show aggregated pipeline health report."""
    health_file = HEALTH_DIR / "pipeline_health.json"

    if not health_file.exists():
        print("  No cached report — running live check...")
        from pulse.daemons.runtime.daemon_heartbeat import check_pipeline_health
        report = check_pipeline_health(verbose=False)
    else:
        try:
            report = json.loads(health_file.read_text(encoding="utf-8"))
        except Exception:
            print("  Failed to read pipeline_health.json")
            return

    status = report.get("status", "UNKNOWN")
    ts = (report.get("timestamp") or "unknown")[:19]
    alerts = report.get("alerts", [])
    brain_alerts = report.get("brain_alerts", [])
    comp = report.get("components", {})

    print("=" * 55)
    print(f"  Pipeline Health: {status}")
    print(f"  Last check: {ts}")
    print("=" * 55)

    # Orchestrator
    orch = comp.get("orchestrator", {})
    print(f"\n  Orchestrator:    {'RUNNING' if orch.get('running') else 'DOWN'}")

    # Daemons
    d = comp.get("daemons", {})
    dead_s = f" ({d.get('dead', 0)} dead)" if d.get("dead") else ""
    print(f"  Daemons:         {d.get('alive', 0)}/{d.get('total', 0)} alive{dead_s}")

    # Heartbeats
    hb = comp.get("heartbeats", {})
    stale_s = f" ({len(hb.get('stale', []))} stale)" if hb.get("stale") else ""
    print(f"  Schedulers:      {hb.get('reporting', 0)} reporting{stale_s}")
    if hb.get("hung_suspects"):
        print(f"    HUNG: {', '.join(hb['hung_suspects'])}")

    # Workers
    w = comp.get("workers", {})
    if w.get("total", 0):
        stale_w = f" ({w.get('stale', 0)} stale)" if w.get("stale") else ""
        print(f"  Workers:         {w.get('alive', 0)}/{w.get('total', 0)} alive{stale_w}")

    # Capture logs
    cl = comp.get("capture_logs", {})
    growth = "GROWING" if cl.get("growing") else "IDLE"
    print(f"  Capture Logs:    {cl.get('total_mb', 0)}MB ({growth})")

    # Evidence
    ev = comp.get("evidence", {})
    ev_age = ev.get("age_s", 999999)
    freshness = "FRESH" if ev.get("fresh") else "STALE"
    print(f"  Evidence:        {freshness} (last write: {_age_str(ev_age)} ago)")

    # Brain health
    bh = comp.get("brain_health", {})
    if bh:
        print(f"  Brain (6h):      {bh.get('status', '?')} (checked: {bh.get('last_check', '?')})")

    # Alerts
    all_alerts = alerts + brain_alerts
    if all_alerts:
        print(f"\n  Alerts ({len(all_alerts)}):")
        for a in all_alerts:
            print(f"    ! {a}")
    else:
        print("\n  All systems nominal.")

    print(f"\n{'=' * 55}")
