"""Wire up hooks and MCP for QuickCall recommendations delivery."""

from __future__ import annotations

import json
import stat
import sys
from pathlib import Path


HOOK_SCRIPT = '''\
#!/bin/bash
# QuickCall recommendations hook — injects accepted rules into AI context
# Installed by: quickcall init recs

QC_DIR="${QC_TRACE_CONFIG_DIR:-$HOME/.quickcall-trace}"
PROJECT_DIR="${CLAUDE_PROJECT_DIR:-$(pwd)}"

# Resolve repo slug from git remote
REMOTE=$(git -C "$PROJECT_DIR" remote get-url origin 2>/dev/null)
if [ -z "$REMOTE" ]; then
    exit 0
fi
# Extract org/repo from SSH or HTTPS remote, replace / with --
SLUG=$(echo "$REMOTE" | sed -E 's#.*[:/]([^/]+/[^/]+)$#\\1#' | sed -E 's#\\.git$##' | sed 's#/#--#')

RULES_FILE="$QC_DIR/recs/$SLUG/rules.json"
if [ ! -f "$RULES_FILE" ]; then
    exit 0
fi

# Output accepted rules for AI context
export RULES_FILE
python3 -c "
import json, sys, os
try:
    data = json.load(open(os.environ['RULES_FILE']))
    rules = data.get('rules', [])
    accepted = [r for r in rules if r.get('status') == 'accepted']
    pending = [r for r in rules if r.get('status') in ('pending', 'open')]
    if accepted:
        print('[QuickCall Rules for ' + data.get('repo', 'unknown') + ']')
        print()
        print('FOLLOW THESE RULES:')
        for r in accepted:
            print('- ' + r['rule'])
        print()
    if pending:
        print('IMPORTANT: There are ' + str(len(pending)) + ' pending QuickCall recommendations.')
        print('Call the review_rules tool from the quickcall-recs MCP server to review them.')
except Exception:
    pass
" 2>/dev/null
'''


def init_recs(base_dir: Path, claude_dir: Path) -> None:
    """Wire up hooks and MCP for recs delivery.

    1. Write inject-rules.sh hook script
    2. Add UserPromptSubmit hook to ~/.claude/settings.json
    3. Add quickcall-recs MCP server to ~/.claude/.mcp.json
    """
    _write_hook_script(base_dir)
    _add_settings_hook(base_dir, claude_dir)
    _add_mcp_server(claude_dir)


def _write_hook_script(base_dir: Path) -> Path:
    """Write inject-rules.sh and make it executable."""
    hooks_dir = base_dir / "hooks"
    hooks_dir.mkdir(parents=True, exist_ok=True)
    script_path = hooks_dir / "inject-rules.sh"
    script_path.write_text(HOOK_SCRIPT)
    script_path.chmod(script_path.stat().st_mode | stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH)
    return script_path


def _add_settings_hook(base_dir: Path, claude_dir: Path) -> None:
    """Add UserPromptSubmit hook to settings.json (idempotent)."""
    settings_path = claude_dir / "settings.json"
    settings: dict = {}
    if settings_path.exists():
        try:
            settings = json.loads(settings_path.read_text())
        except (json.JSONDecodeError, OSError):
            pass

    hooks = settings.setdefault("hooks", {})
    user_prompt_hooks: list = hooks.setdefault("UserPromptSubmit", [])

    hook_command = str(base_dir / "hooks" / "inject-rules.sh")

    # Check if already wired
    for entry in user_prompt_hooks:
        for h in entry.get("hooks", []):
            if h.get("command") == hook_command:
                return  # Already exists

    user_prompt_hooks.append({
        "hooks": [{
            "type": "command",
            "command": hook_command,
            "timeout": 5,
        }]
    })

    settings_path.parent.mkdir(parents=True, exist_ok=True)
    settings_path.write_text(json.dumps(settings, indent=2) + "\n")


def _add_mcp_server(claude_dir: Path) -> None:
    """Add quickcall-recs MCP server to .mcp.json (idempotent)."""
    mcp_path = claude_dir / ".mcp.json"
    mcp_config: dict = {}
    if mcp_path.exists():
        try:
            mcp_config = json.loads(mcp_path.read_text())
        except (json.JSONDecodeError, OSError):
            pass

    servers = mcp_config.setdefault("mcpServers", {})
    if "quickcall-recs" in servers:
        return  # Already exists

    command, args = _find_quickcall_bin()

    servers["quickcall-recs"] = {
        "command": command,
        "args": args,
    }

    mcp_path.parent.mkdir(parents=True, exist_ok=True)
    mcp_path.write_text(json.dumps(mcp_config, indent=2) + "\n")


def _find_quickcall_bin() -> tuple[str, list[str]]:
    """Find the quickcall binary path, returning (command, args)."""
    import shutil
    path = shutil.which("quickcall")
    if path:
        return (path, ["mcp-recs"])
    # Fallback: use sys.executable with -m to invoke as module
    return (sys.executable, ["-m", "qc_trace.cli.traced", "mcp-recs"])
