"""obol status - quick overview of your Obol deployment."""
from obol.cli._base import (
    get_api, handle_api_error, output, score_bar, compliance_bar,
    CHAR_TL, CHAR_TR, CHAR_BL, CHAR_BR, CHAR_DLINE, CHAR_VLINE,
)


@handle_api_error
def cmd_status(args):
    api = get_api()
    fmt = getattr(args, "format", "text")

    # Gather data from multiple endpoints
    try:
        agents_data = api.list_agents()
    except Exception:
        agents_data = {"agents": [], "count": 0}

    try:
        compliance_data = api.get_compliance_status()
    except Exception:
        compliance_data = None

    try:
        alerts_data = api.list_alerts(limit=5)
    except Exception:
        alerts_data = {"alerts": [], "open_count": 0, "critical_count": 0}

    if fmt == "json":
        output({
            "agents": agents_data,
            "compliance": compliance_data,
            "alerts": alerts_data,
        }, fmt="json")
        return

    # Header
    print(f"{CHAR_TL}{CHAR_DLINE * 38}{CHAR_TR}")
    print(f"{CHAR_VLINE}          OBOL STATUS                 {CHAR_VLINE}")
    print(f"{CHAR_BL}{CHAR_DLINE * 38}{CHAR_BR}")
    print()

    # Agents
    agents = agents_data.get("agents", [])
    active = sum(1 for a in agents if a.get("active", False))
    print(f"  Agents:     {active} active / {len(agents)} total")

    # Trust scores
    scores = [a.get("trust_score", 0) for a in agents if a.get("active")]
    if scores:
        avg = sum(scores) / len(scores)
        print(f"  Avg Trust:  {score_bar(avg)}")
    else:
        print("  Avg Trust:  (no active agents)")

    print()

    # Compliance
    if compliance_data and compliance_data.get("compliance_enabled"):
        score = compliance_data.get("overall_score")
        gaps = compliance_data.get("gaps", 0)
        stale = " (stale)" if compliance_data.get("stale") else ""
        print(f"  Compliance: {compliance_bar(score)}{stale}")
        print(f"  Gaps:       {gaps}")

        regs = compliance_data.get("regulations", [])
        if regs:
            print()
            for reg in regs:
                s = reg.get("score")
                name = reg.get("name", reg.get("slug", "?"))
                bar = compliance_bar(s) if s is not None else "(not computed)"
                g = reg.get("gaps", 0)
                gap_str = f"  ({g} gaps)" if g > 0 else ""
                print(f"    {name:<30} {bar}{gap_str}")
    else:
        print("  Compliance: not configured")
        print("  Run: obol compliance profile --industry <X> --jurisdictions <Y>")

    print()

    # Alerts
    open_count = alerts_data.get("open_count", 0)
    critical = alerts_data.get("critical_count", 0)
    if open_count > 0:
        print(f"  Alerts:     {open_count} open ({critical} critical)")
        for alert in alerts_data.get("alerts", [])[:3]:
            sev = alert.get("severity", "?")
            title = alert.get("title", "?")
            print(f"    [{sev.upper():>8}] {title}")
    else:
        print("  Alerts:     none open")

    print()
