"""obol alerts - view and manage alerts."""
from obol.cli._base import get_api, handle_api_error, output, table, add_format_arg


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

    sub = getattr(args, "alerts_cmd", None)

    if sub == "resolve":
        result = api.resolve_alert(args.alert_id, status="resolved")
        if fmt == "json":
            output(result, fmt="json")
        else:
            print(f"Alert #{args.alert_id} resolved.")
        return

    if sub == "acknowledge":
        result = api.resolve_alert(args.alert_id, status="acknowledged")
        if fmt == "json":
            output(result, fmt="json")
        else:
            print(f"Alert #{args.alert_id} acknowledged.")
        return

    # Default: list
    status_filter = None
    if getattr(args, "unresolved", False):
        status_filter = "open"

    data = api.list_alerts(
        status=status_filter,
        severity=getattr(args, "severity", None),
        limit=getattr(args, "limit", 50),
    )

    if fmt == "json":
        output(data, fmt="json")
        return

    alerts = data.get("alerts", [])
    if not alerts:
        print("No alerts.")
        return

    print(f"Alerts: {data.get('count', len(alerts))} shown / {data.get('total', '?')} total "
          f"({data.get('open_count', 0)} open, {data.get('critical_count', 0)} critical)")
    print()

    rows = []
    for a in alerts:
        sev = a.get("severity", "?")
        sev_display = {"critical": "CRIT", "high": "HIGH", "medium": "MED", "low": "LOW"}.get(sev, sev)
        rows.append([
            a["id"],
            sev_display,
            a.get("alert_type", "-"),
            a.get("title", "-"),
            a.get("status", "-"),
            str(a.get("created_at", "-"))[:19],
        ])

    table(
        ["ID", "Sev", "Type", "Title", "Status", "Created"],
        rows,
        max_widths={3: 35, 5: 19},
    )


def setup_parser(subparsers):
    """Add alerts subparser."""
    parser = subparsers.add_parser("alerts", help="Alert management")
    parser.set_defaults(func=cmd_alerts, alerts_cmd=None)
    add_format_arg(parser)
    parser.add_argument("--unresolved", action="store_true", help="Show only open alerts")
    parser.add_argument("--severity", help="Filter by severity")
    parser.add_argument("--limit", type=int, default=50, help="Max results")

    sub = parser.add_subparsers(dest="alerts_cmd")

    resolve = sub.add_parser("resolve", help="Resolve an alert")
    resolve.add_argument("alert_id", type=int)

    ack = sub.add_parser("acknowledge", help="Acknowledge an alert")
    ack.add_argument("alert_id", type=int)
