"""CLI commands: diagnostics / system tests."""

from __future__ import annotations

from proxym.cli._client import make_client, print_json_if_yaml, print_table


def cmd_tests_status(args):
    """Run all diagnostic tests and show results."""
    with make_client() as c:
        r = c.get("/tests/status")
        data = r.json()

    if print_json_if_yaml(args, data):
        return

    status = data.get("overall_status", "unknown")
    passed = data.get("passed", 0)
    failed = data.get("failed", 0)
    total = data.get("total", 0)

    color = "\033[32m" if status == "healthy" else "\033[33m"
    print(f"\n  {color}System: {status.upper()}\033[0m  ({passed}/{total} passed)\n")

    for t in data.get("tests", []):
        icon = "✓" if t.get("passed") else "✗"
        c = "\033[32m" if t.get("passed") else "\033[31m"
        service = t.get("service", "?")
        msg = t.get("message", "")
        print(f"  {c}{icon}\033[0m  {service:<20} {msg}")
        for issue in t.get("issues", []):
            print(f"       ↳ {issue}")
    print()


def cmd_test_vscode(args):
    """Test VS Code Web connectivity."""
    with make_client() as c:
        r = c.get("/tests/vscode")
        data = r.json()

    reachable = data.get("reachable", False)
    icon = "✓" if reachable else "✗"
    color = "\033[32m" if reachable else "\033[31m"
    print(f"  {color}{icon} VS Code Web: {'reachable' if reachable else 'NOT reachable'}\033[0m")
    print(f"    URL: {data.get('url', '?')}")
    if data.get("password_configured"):
        print(f"    Password: configured")


def cmd_test_proxy(args):
    """Test LLM proxy connectivity."""
    with make_client() as c:
        r = c.get("/tests/proxy")
        data = r.json()

    reachable = data.get("reachable", False)
    icon = "✓" if reachable else "✗"
    color = "\033[32m" if reachable else "\033[31m"
    print(f"  {color}{icon} LLM Proxy: {'reachable' if reachable else 'NOT reachable'}\033[0m")
    print(f"    Models: {data.get('models_available', 0)}")


def cmd_test_providers(args):
    """Check configured LLM providers."""
    with make_client() as c:
        r = c.get("/tests/providers")
        data = r.json()

    if print_json_if_yaml(args, data):
        return

    providers = data.get("providers", [])
    print(f"\n  Providers ({data.get('total_providers', 0)})\n")
    for p in providers:
        icon = "✓" if p.get("has_key") or p.get("is_local") else "✗"
        color = "\033[32m" if p.get("has_key") or p.get("is_local") else "\033[31m"
        print(f"  {color}{icon}\033[0m  {p['name']}")

    aliases = data.get("aliases", [])
    if aliases:
        print(f"\n  Aliases ({len(aliases)})\n")
        for a in aliases:
            icon = "✓" if a.get("available") else "✗"
            color = "\033[32m" if a.get("available") else "\033[31m"
            print(f"  {color}{icon}\033[0m  {a['alias']} → {a['model']} ({a['provider']})")
    print()


def cmd_test_extensions(args):
    """Check installed VS Code extensions."""
    with make_client() as c:
        r = c.get("/tests/extensions")
        data = r.json()

    if print_json_if_yaml(args, data):
        return

    print(f"\n  Extensions ({data.get('total_installed', 0)} installed)\n")
    for m in data.get("missing_required", []):
        print(f"  \033[31m✗ missing: {m}\033[0m")
    for m in data.get("missing_vsix", []):
        print(f"  \033[33m⚠ vsix-only: {m}\033[0m")
    for m in data.get("conflicting", []):
        print(f"  \033[31m⚠ conflicting: {m}\033[0m")
    if not data.get("missing_required") and not data.get("conflicting"):
        print("  \033[32m✓ All required extensions installed.\033[0m")
    print()


def cmd_test_agent_setup(args):
    """Comprehensive agent readiness check."""
    with make_client() as c:
        r = c.get("/tests/agent-setup")
        data = r.json()

    ready = data.get("ready", False)
    color = "\033[32m" if ready else "\033[31m"
    print(f"\n  {color}Agent: {'READY' if ready else 'NOT READY'}\033[0m\n")

    for check in data.get("checks", []):
        icon = "✓" if check.get("pass") else "✗"
        c = "\033[32m" if check.get("pass") else "\033[31m"
        print(f"  {c}{icon}\033[0m  {check.get('name', '?')}")
        if check.get("detail"):
            print(f"       {check['detail']}")
    print()


def cmd_test_agent(args):
    """Test agent with a simple completion."""
    with make_client() as c:
        r = c.get("/tests/agent")
        data = r.json()

    success = data.get("success", False)
    icon = "✓" if success else "✗"
    color = "\033[32m" if success else "\033[31m"
    print(f"  {color}{icon} Agent test: {'passed' if success else 'failed'}\033[0m")
    if data.get("response_time_ms"):
        print(f"    Response time: {data['response_time_ms']}ms")
    details = data.get("details", {})
    if details.get("response"):
        print(f"    Response: {details['response']}")
    if details.get("error"):
        print(f"    Error: {details['error']}")
    if details.get("skipped"):
        print(f"    Skipped: {details['skipped']}")
