"""obol diagnose - verify Obol installation and coverage.

Usage:
    obol diagnose

Checks all installed agents, hooks, interceptors, and verifies
that monitoring is working correctly.
"""
import json
import os
import sys


def setup_parser(subparsers):
    p = subparsers.add_parser("diagnose", help="Verify Obol installation and coverage")
    p.add_argument("--verbose", "-v", action="store_true", help="Show detailed output")
    p.set_defaults(func=cmd_diagnose)


def cmd_diagnose(args):
    # Imports available if needed - table, secure_file from _base
    # Currently using print() directly for formatted output

    print()
    print("  OBOL DIAGNOSTICS")
    print("  Verifying installation and coverage")
    print()

    issues = []
    warnings = []

    # --- Check config ---
    print("  [1/6] Configuration")
    config_path = os.path.expanduser("~/.obol/config.json")
    config = {}
    if os.path.exists(config_path):
        try:
            with open(config_path) as f:
                config = json.load(f)
            print("        ~/.obol/config.json exists")

            if config.get("api_key"):
                key = config["api_key"]
                print(f"        API key: {key[:12]}...{key[-4:]}")
            else:
                issues.append("No API key configured")
                print("        API key: MISSING")

            mode = config.get("enforcement_mode", "audit")
            print(f"        Enforcement mode: {mode}")

        except Exception as e:
            issues.append(f"Config file corrupted: {e}")
            print(f"        Config file corrupted: {e}")
    else:
        issues.append("~/.obol/config.json not found")
        print("        ~/.obol/config.json NOT FOUND")
    print()

    # --- Check API connection ---
    print("  [2/6] API Connection")
    if config.get("api_key"):
        from obol.api import ObolAPI, ObolAPIError
        api_url = config.get("api_url", "https://obol.grayowlresearch.com/v1")
        api = ObolAPI(config["api_key"], api_url)
        try:
            result = api._request("GET", "/agents")
            agent_count = len(result.get("agents", []))
            print(f"        Connected to {api_url}")
            print(f"        {agent_count} agent(s) registered")
        except ObolAPIError as e:
            issues.append(f"API error: {e.detail}")
            print(f"        API error: {e.detail}")
        except Exception as e:
            issues.append(f"Cannot reach API: {e}")
            print(f"        Cannot reach API: {e}")
    else:
        print("        Skipped (no API key)")
    print()

    # --- Check installed agents ---
    print("  [3/6] Detected Agents")
    from obol.registry import detect_installed, KNOWN_AGENTS

    found = detect_installed()
    if found:
        for agent in found:
            slug = agent["slug"]
            method = agent["wrap_method"]
            config_key = f"{slug.replace('-', '_')}_agent_id"
            agent_id = config.get(config_key)
            status = f"registered (#{agent_id})" if agent_id else "NOT registered"
            print(f"        {agent['name']}: {status}")
            print(f"          Wrap method: {method}")
    else:
        warnings.append("No known AI agents detected on this machine")
        print("        No known agents detected")
    print()

    # --- Check hooks ---
    print("  [4/6] Hook Installation")
    hook_checks = [
        ("Claude Code", "~/.claude/settings.json", "hooks", ["obol", "handler.py"]),
        ("Cursor", "~/.cursor/hooks.json", None, ["obol"]),
        ("Windsurf", "~/.codeium/windsurf/hooks.json", None, ["obol"]),
    ]

    for name, path, nested_key, markers in hook_checks:
        full_path = os.path.expanduser(path)
        if os.path.exists(full_path):
            try:
                with open(full_path) as f:
                    data = json.load(f)
                if nested_key:
                    data = data.get(nested_key, {})

                data_str = json.dumps(data)
                has_obol = all(m in data_str for m in markers)

                if has_obol:
                    print(f"        {name}: Obol hooks installed")
                else:
                    print(f"        {name}: config exists, Obol NOT installed")
                    warnings.append(f"{name} detected but Obol hooks not installed")
            except Exception as e:
                print(f"        {name}: config corrupted ({e})")
        else:
            print(f"        {name}: not installed")

    # Check handler files
    handler_files = [
        ("~/.obol/handler.py", "Claude Code PostToolUse"),
        ("~/.obol/gate.py", "Claude Code PreToolUse"),
        ("~/.obol/cursor_handler.py", "Cursor"),
        ("~/.obol/windsurf_handler.py", "Windsurf"),
    ]

    for path, desc in handler_files:
        full_path = os.path.expanduser(path)
        if os.path.exists(full_path):
            # Check permissions
            mode = os.stat(full_path).st_mode & 0o777
            if mode == 0o444:
                print(f"        {path}: OK (read-only)")
            else:
                warnings.append(f"{path} is writable (should be 444)")
                print(f"        {path}: WARNING (mode {oct(mode)}, should be 444)")
    print()

    # --- Check Python interceptors ---
    print("  [5/6] Python Framework Interceptors")
    frameworks = [
        ("langchain_core", "langchain", "LangChain"),
        ("crewai", "crewai", "CrewAI"),
        ("autogen", "autogen", "AutoGen"),
        ("pyautogen", "autogen", "AutoGen (pyautogen)"),
        ("openai", "openai_sdk", "OpenAI SDK"),
    ]

    import importlib.util
    for pkg, interceptor_name, display in frameworks:
        spec = importlib.util.find_spec(pkg)
        if spec:
            print(f"        {display}: installed")
            # Check if interceptor can be loaded
            try:
                mod = importlib.import_module(f"obol.interceptors.{interceptor_name}")
                if hasattr(mod, "install") and hasattr(mod, "is_installed"):
                    print(f"          Interceptor: available")
                    if args.verbose:
                        print(f"          To instrument: obol.interceptors.{interceptor_name}.install()")
            except ImportError:
                print(f"          Interceptor: NOT available")
        else:
            if args.verbose:
                print(f"        {display}: not installed")
    print()

    # --- Check local fallback ---
    print("  [6/6] Local Fallback")
    fallback_path = os.path.expanduser("~/.obol/failed_events.jsonl")
    if os.path.exists(fallback_path):
        try:
            with open(fallback_path) as f:
                lines = f.readlines()
            if lines:
                warnings.append(f"{len(lines)} failed events pending retry")
                print(f"        {len(lines)} failed event(s) pending")
                print("        Run: obol retry")
            else:
                print("        No failed events")
        except Exception as e:
            print(f"        Could not read: {e}")
    else:
        print("        No fallback file (good)")
    print()

    # --- Summary ---
    print("  " + "=" * 48)
    print()

    if issues:
        print("  ISSUES (must fix):")
        for issue in issues:
            print(f"    - {issue}")
        print()

    if warnings:
        print("  WARNINGS (optional):")
        for warning in warnings:
            print(f"    - {warning}")
        print()

    if not issues and not warnings:
        print("  All checks passed. Obol is properly configured.")
    elif not issues:
        print("  Obol is functional. Warnings are informational.")
    else:
        print("  Run 'obol setup' to fix issues.")
    print()

    # Return exit code
    return 1 if issues else 0
