"""Re-sync tribunal hooks and settings into ~/.claude/settings.json.

Extracted from ``launcher/cli.py`` to keep that module under the 300-line
target.  The public surface (``_run_repair``) is re-exported from cli.py
so existing imports continue to work.
"""

from __future__ import annotations

import json
import os
import shutil

_PLUGIN_ROOT: str = os.path.expanduser("~/.claude/tribunal")
_CLAUDE_SETTINGS_PATH: str = os.path.expanduser("~/.claude/settings.json")


def _run_repair() -> None:
    """Re-sync tribunal hooks and settings into ~/.claude/settings.json.

    Safe to run multiple times — merges additive changes only, never removes
    existing user settings.  Useful after a manual rsync-based update or when
    hooks stop firing.
    """
    plugin_root = _PLUGIN_ROOT
    hooks_path = os.path.join(plugin_root, "hooks", "hooks.json")
    sf_settings_path = os.path.join(plugin_root, "settings.json")
    claude_settings_path = _CLAUDE_SETTINGS_PATH

    if not os.path.exists(hooks_path):
        print(f"[!!] Hooks file not found: {hooks_path}")
        return

    if os.path.exists(claude_settings_path):
        shutil.copy2(claude_settings_path, claude_settings_path + ".bak")

    settings: dict = {}
    if os.path.exists(claude_settings_path):
        with open(claude_settings_path) as f:
            settings = json.load(f)

    with open(hooks_path) as f:
        raw = f.read().replace("$CLAUDE_PLUGIN_ROOT", plugin_root).replace("${CLAUDE_PLUGIN_ROOT}", plugin_root)
    hooks_data = json.loads(raw)
    settings["hooks"] = hooks_data.get("hooks", {})
    counts = {k: len(v) for k, v in settings["hooks"].items()}
    print(f"[OK] Hooks registered: {counts}")

    if os.path.exists(sf_settings_path):
        with open(sf_settings_path) as f:
            sf = json.load(f)
        sf_env = sf.get("env", {})
        settings_env = settings.setdefault("env", {})
        added_env = [k for k, v in sf_env.items() if k not in settings_env and not settings_env.update({k: v})]  # type: ignore[func-returns-value]
        if added_env:
            print(f"[OK] Env vars added: {added_env}")
        sf_allow = sf.get("permissions", {}).get("allow", [])
        settings_allow = settings.setdefault("permissions", {}).setdefault("allow", [])
        added_perms = [p for p in sf_allow if p not in settings_allow]
        settings_allow.extend(added_perms)
        if added_perms:
            print(f"[OK] Permissions added: {added_perms}")
        if "statusCommand" not in settings and "statusCommand" in sf:
            settings["statusCommand"] = sf["statusCommand"]
            print("[OK] statusCommand set")

    with open(claude_settings_path, "w") as f:
        json.dump(settings, f, indent=2)

    print("[OK] Repair complete. Restart Claude Code to pick up hook changes.")
