"""CLI commands for observability and repair."""
from __future__ import annotations

import click

from proxym.cli._client import make_client, print_json


def cmd_obs_errors(args):
    client = make_client(args.proxy, args.key)
    r = client.get("/observability/errors")
    r.raise_for_status()
    data = r.json()
    click.echo(f"  Errors: {data['total_errors']}/{data['total_logs']} logs")
    for src, count in data.get("by_source", {}).items():
        click.echo(f"    {src}: {count}")


def cmd_obs_health(args):
    client = make_client(args.proxy, args.key)
    r = client.get("/observability/health-summary")
    r.raise_for_status()
    data = r.json()
    click.echo(f"  Active issues: {data['active_issues']} ({data['critical']} critical)")
    for evt in data.get("recent", []):
        icon = {"critical": "\u274c", "warning": "\u26a0\ufe0f", "resolved": "\u2705"}.get(evt["severity"], "\u2b55")
        click.echo(f"  {icon} [{evt['source']}] {evt['title']}")


def cmd_obs_repair(args):
    import httpx
    if getattr(args, "from_logs", False):
        r = httpx.post(
            f"{args.proxy}/observability/repair-from-logs",
            headers={"Authorization": f"Bearer {args.key}"},
            timeout=60,
        )
    else:
        error_text = getattr(args, "error", "") or ""
        mode = getattr(args, "mode", "suggest") or "suggest"
        r = httpx.post(
            f"{args.proxy}/observability/repair",
            json={"error_text": error_text, "mode": mode},
            headers={"Authorization": f"Bearer {args.key}"},
            timeout=60,
        )
    r.raise_for_status()
    data = r.json()
    if "error" in data:
        click.echo(f"  Error: {data['error']}")
        return
    click.echo(f"  Diagnosis: {data.get('diagnosis', '?')}")
    click.echo(f"  Suggestion: {data.get('suggestion', '?')}")
    if data.get("applied"):
        click.echo(f"  Fix applied — tests: {data.get('test_result', '?')}")
    elif data.get("diff"):
        click.echo(f"  Diff available ({len(data['diff'])} chars) — use --mode apply to auto-apply")


def cmd_obs_logs(args):
    client = make_client(args.proxy, args.key)
    params = {"limit": getattr(args, "limit", 50)}
    level = getattr(args, "level", None)
    if level:
        params["level"] = level
    r = client.get("/observability/logs", params=params)
    r.raise_for_status()
    data = r.json()
    for entry in data:
        ts = entry.get("timestamp", 0)
        lvl = entry.get("level", "?").upper()
        src = entry.get("source", "?")
        evt = entry.get("event", "")
        click.echo(f"  {lvl:7s}  {src}  {evt}")
