"""obol whoami - show account and environment info."""
import json
import os

from obol.cli._base import (
    get_api, handle_api_error, output, add_format_arg,
    CHAR_TL, CHAR_TR, CHAR_BL, CHAR_BR, CHAR_DLINE, CHAR_VLINE,
    CHAR_CHECK, CHAR_CROSS, CHAR_ACTIVE, CHAR_INACTIVE,
)


CONFIG_PATH = os.path.expanduser("~/.obol/config.json")
SETTINGS_PATH = os.path.expanduser("~/.claude/settings.json")


def _load_config():
    if os.path.exists(CONFIG_PATH):
        try:
            with open(CONFIG_PATH) as f:
                return json.load(f)
        except Exception:
            return {}
    return {}


def _mask_key(key):
    """Mask an API key for display."""
    if not key or len(key) <= 14:
        return "***"
    return key[:10] + "..." + key[-4:]


def _check_hooks():
    """Check if Obol hooks are installed in Claude Code settings.

    Returns (installed: bool, hook_events: list[str]).
    """
    if not os.path.exists(SETTINGS_PATH):
        return False, []

    try:
        with open(SETTINGS_PATH) as f:
            settings = json.load(f)
    except Exception:
        return False, []

    hooks = settings.get("hooks", {})
    obol_events = []
    for event, entries in hooks.items():
        if "obol" in json.dumps(entries).lower():
            obol_events.append(event)

    return bool(obol_events), obol_events


def _is_disabled():
    """Check if monitoring is disabled (saved hooks file exists)."""
    return os.path.exists(os.path.expanduser("~/.obol/disabled_hooks.json"))


@handle_api_error
def cmd_whoami(args):
    fmt = getattr(args, "format", "text")
    config = _load_config()
    api_key = config.get("api_key", os.environ.get("OBOL_API_KEY", ""))
    api_url = config.get("api_url", os.environ.get(
        "OBOL_API_URL", "https://obol.grayowlresearch.com/v1"
    ))
    hooks_installed, hook_events = _check_hooks()
    disabled = _is_disabled()

    # Try to fetch remote info
    remote_info = {}
    if api_key:
        try:
            api = get_api()
            agents_data = api.list_agents()
            agents = agents_data.get("agents", [])
            active = sum(1 for a in agents if a.get("active", False))
            remote_info["agents_total"] = len(agents)
            remote_info["agents_active"] = active
            remote_info["connected"] = True
        except SystemExit:
            # get_api calls error() which does sys.exit -- catch it
            remote_info["connected"] = False
        except Exception:
            remote_info["connected"] = False

    if fmt == "json":
        data = {
            "api_key": _mask_key(api_key) if api_key else None,
            "api_url": api_url,
            "config_path": CONFIG_PATH,
            "config_exists": os.path.exists(CONFIG_PATH),
            "hooks_installed": hooks_installed,
            "hooks_disabled": disabled,
            "hook_events": hook_events,
        }
        data.update(remote_info)
        output(data, fmt="json")
        return

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

    # API key
    if api_key:
        key_source = "config" if config.get("api_key") else "env"
        print(f"  API Key:    {_mask_key(api_key)} ({key_source})")
    else:
        print(f"  API Key:    (not configured)")

    # API URL
    print(f"  API URL:    {api_url}")

    # Connection status
    connected = remote_info.get("connected", False)
    if connected:
        print(f"  Connection: {CHAR_CHECK} connected")
    elif api_key:
        print(f"  Connection: {CHAR_CROSS} could not reach API")
    else:
        print(f"  Connection: {CHAR_CROSS} no API key")

    print()

    # Agents (from remote)
    if connected:
        total = remote_info.get("agents_total", 0)
        active = remote_info.get("agents_active", 0)
        print(f"  Agents:     {active} active / {total} registered")

    # Hooks
    if hooks_installed and not disabled:
        print(f"  Hooks:      {CHAR_ACTIVE} active ({', '.join(hook_events)})")
    elif disabled:
        print(f"  Hooks:      {CHAR_INACTIVE} disabled (run: obol enable)")
    elif hooks_installed:
        print(f"  Hooks:      {CHAR_ACTIVE} installed ({', '.join(hook_events)})")
    else:
        print(f"  Hooks:      {CHAR_INACTIVE} not installed (run: obol setup)")

    print()

    # Local config
    if os.path.exists(CONFIG_PATH):
        print(f"  Config:     {CONFIG_PATH}")
    else:
        print(f"  Config:     (not found) Run: obol setup")

    # Local audit log
    audit_dir = os.path.expanduser("~/.obol/audit")
    if os.path.isdir(audit_dir):
        try:
            files = os.listdir(audit_dir)
            print(f"  Audit log:  {len(files)} file(s) in ~/.obol/audit/")
        except Exception:
            print(f"  Audit log:  ~/.obol/audit/")
    else:
        print(f"  Audit log:  (none)")

    print()


def setup_parser(subparsers):
    """Add whoami subparser."""
    parser = subparsers.add_parser("whoami", help="Show account and environment info")
    parser.set_defaults(func=cmd_whoami)
    add_format_arg(parser)
