#!/usr/bin/env python3
"""Fail on any registered guard that does not run through the fail-safe wrapper.

hook-audit finds a guard that crashes, after the fact. This makes the rule itself the check: every
PreToolUse command registered in the settings files must be a Python hook that calls
`_hookfail.run(` (rstack/hooks/_hookfail.py), or be on an allowlist with a reason. A shell guard
counts only through a Python shim that uses the wrapper, because a shell script that errors exits
nonzero and Claude Code lets the call through. The one shell shape that passes is a trampoline:
`python3 "$(dirname "$0")/X.py" && exit 0` then `exit 2`, where X.py uses the wrapper. A registered hook whose file is missing is a guard
that is not there, and fails too.

Why (11-10): hook-audit on a KB project found three send gates (a friend-reply gate, a voice gate,
an email gate) that crashed on malformed events and so failed open. None used the wrapper. The
laptop, which had adopted the same wrapper, found its only crash in the one guard that didn't.

    hook-wrap-check [SETTINGS.json ...] [--project DIR] [--allow FILE] [--json]

Default settings: ~/.claude/settings.json, plus DIR/.claude/settings.json for each --project.

Allowlist (default $RSTACK_HOOK_ALLOWLIST, else ~/.config/rstack/hook-allowlist.json):
    {"allow": {"<hook file name>": {"reason": "why it is safe unwrapped", "until": "YYYY-MM-DD"}},
     "projects": ["~/path/to/project"]}
A reason is required. `until` is optional; after that date the entry no longer counts, so a
temporary exception (a migration in progress) cannot become a permanent one. `projects` are added
to --project, so a host's policy file names the project settings it holds to the same rule.

A wrapped hook is DRIFTED when the _hookfail.py it imports (its own directory's, or ~/.claude/hooks/
for a project hook that names that path) is not byte-identical to this checkout's copy: an old
wrapper lacks the lookup and fail_closed answers, so it is installed from main, not edited.

Two more failures (11-11, from the laptop's use of the same wrapper):
  BROAD_CLOSED  a guard with fail_closed=True on a matcher that covers every shell command (Bash), every
                file edit (Edit, Write, MultiEdit, NotebookEdit), every browser click (the computer tools) or
                every tool (*): fail_closed ignores triage, so one bug in it refuses the whole session.
  STALE         an allowlist entry that has expired, names no registered hook, or covers a hook that is now
                wrapped. A dead exception is how a temporary one becomes permanent unnoticed.

Exit 0 when every guard is wrapped (with the current wrapper) or allowed, 1 otherwise.
"""
import argparse
import datetime as dt
import json
import os
from pathlib import Path
import re
import shlex
import sys

MARK = '_hookfail.run('
SCRIPT = re.compile(r'\.(py|sh|bash|zsh)$')


LIB = Path(__file__).resolve().parents[1] / 'hooks/_hookfail.py'   # the committed copy beside this tool


def lib_of(script, text):
    """The _hookfail.py a wrapped hook imports: its own directory's, else ~/.claude/hooks/ when it
    names that path (the KB send gates do). None when it names neither."""
    sibling = script.parent / '_hookfail.py'
    if sibling.is_file() or ('.claude/hooks' not in text and "'.claude', 'hooks'" not in text):
        return sibling
    return Path.home() / '.claude/hooks/_hookfail.py'


def drift(script, text, lib):
    """None when the hook imports the same _hookfail as `lib`, else why not."""
    used = lib_of(script, text)
    if lib is None or used == lib:
        return None
    if not used.is_file():
        return 'imports {}, which is missing: the hook cannot load its wrapper'.format(used)
    if used.read_bytes() != lib.read_bytes():
        return 'imports {}, which differs from {} (install it from main)'.format(used, lib)
    return None


def policy_path():
    return Path(os.environ.get('RSTACK_HOOK_ALLOWLIST') or
                Path.home() / '.config/rstack/hook-allowlist.json').expanduser()


def load_policy(path):
    """(allow {name: entry}, projects [path]) from the policy file, or empty when it has none."""
    path = Path(path).expanduser()
    if not path.is_file():
        return {}, []
    data = json.loads(path.read_text())
    allow = data.get('allow') or {}
    for name, entry in allow.items():
        if not isinstance(entry, dict) or len(str(entry.get('reason', '')).split()) < 3:
            raise ValueError('{}: allowlist entry {} needs a reason of a few words'.format(path, name))
        if entry.get('until'):
            dt.date.fromisoformat(entry['until'])   # a malformed date is a refusal, not a pass
    return allow, [str(Path(p).expanduser()) for p in data.get('projects') or []]


def registered(paths):
    """Every PreToolUse command: dict(settings, project, matcher, command)."""
    out = []
    for path, project in paths:
        try:
            cfg = json.loads(Path(path).read_text())
        except (OSError, ValueError) as exc:
            out.append(dict(settings=str(path), project=project, matcher='', command='',
                            error='settings unreadable ({})'.format(type(exc).__name__)))
            continue
        for entry in (cfg.get('hooks') or {}).get('PreToolUse', []):
            for h in entry.get('hooks', []):
                if h.get('type') == 'command':
                    out.append(dict(settings=str(path), project=project,
                                    matcher=entry.get('matcher') or '*', command=h.get('command', '')))
    return out


def script_of(command, project):
    """The hook file a command runs: the first word that looks like a script, expanded."""
    try:
        words = shlex.split(command)
    except ValueError:
        words = command.split()
    home = str(Path.home())
    for i, w in enumerate(words):
        w = w.replace('${CLAUDE_PROJECT_DIR}', project or '').replace('$CLAUDE_PROJECT_DIR', project or '')
        w = os.path.expanduser(os.path.expandvars(w.replace('${HOME}', home).replace('$HOME', home)))
        words[i] = w
        if SCRIPT.search(w):
            return Path(w)
    # Python hooks may use an extensionless tool name.
    if words and Path(words[0]).name in ('python', 'python3'):
        scripts = [w for w in words[1:] if not w.startswith('-')]
        if scripts:
            return Path(scripts[0])
    return Path(words[0]) if words else None


TRAMPOLINE = re.compile(r'^python3\s+"?\$\(dirname\s+"\$0"\)"?/([\w.-]+\.py)"?\s+&&\s+exit\s+0$')


def trampoline(script, text):
    """The wrapped .py a shell guard hands off to, when that is all it does; else None.

    11-10 (KB b723a00bc): friend-reply-gate.sh kept its name so settings and references hold, and became
    `python3 "$(dirname "$0")/friend-reply-gate.py" && exit 0` then `exit 2`. That fails closed: if the
    wrapped hook cannot run, the click is refused. Accepted only in exactly that shape (comments and echo
    lines aside), naming a sibling that calls the wrapper. Not `exec python3 ...`: a python that cannot
    start exits 1, and exit 1 is an allow."""
    if script.suffix == '.py':
        return None
    lines = [l.strip() for l in text.splitlines()
             if l.strip() and not l.strip().startswith(('#', 'echo '))]
    m = TRAMPOLINE.match(lines[0]) if lines else None
    if not m or lines[1:] != ['exit 2']:
        return None
    target = script.parent / m.group(1)
    if target.is_file() and MARK in target.read_text(errors='replace'):
        return target
    return None


def verdict(row, allow, today, lib=LIB):
    """('ok'|'allowed'|'UNWRAPPED'|'MISSING'|'BROKEN'|'DRIFTED', detail)."""
    if row.get('error'):
        return 'BROKEN', row['error']
    script = script_of(row['command'], row['project'])
    name = script.name if script else '?'
    entry = allow.get(name)
    live = entry and (not entry.get('until') or dt.date.fromisoformat(entry['until']) >= today)
    if script is None or not script.is_file():
        return ('allowed', entry['reason']) if live else ('MISSING', 'no file at {}'.format(script))
    text = script.read_text(errors='replace')
    python_hook = script.suffix == '.py' or bool(re.match(r'^#![^\n]*\bpython[0-9.]*\b', text))
    if python_hook and MARK in text:
        if re.search(r'fail_closed\s*=\s*True', text) and broad(row['matcher']):
            return 'BROAD_CLOSED', ('{} sets fail_closed=True on [{}], which covers every shell command, file edit, click or tool: '
                                    'use triage instead'.format(name, row['matcher']))
        why = drift(script, text, lib)
        return ('DRIFTED', '{} {}'.format(name, why)) if why else ('ok', name)
    target = trampoline(script, text)
    if target:
        why = drift(target, target.read_text(errors='replace'), lib)
        return ('DRIFTED', '{} runs {}, which {}'.format(name, target.name, why)) if why else \
            ('ok', '{} (runs {}, exit 2 if it cannot)'.format(name, target.name))
    if live:
        return 'allowed', '{} (until {})'.format(entry['reason'], entry['until']) if entry.get('until') \
            else entry['reason']
    if entry and not live:
        return 'UNWRAPPED', '{}: its allowlist entry expired {}'.format(name, entry['until'])
    if not python_hook:
        return 'UNWRAPPED', '{} is a shell guard: register a Python shim that calls {} instead'.format(name, MARK)
    return 'UNWRAPPED', '{} does not call {}'.format(name, MARK)


# Tools whose matcher covers a whole class of everyday calls: every shell command, every file edit,
# every browser click. A fail_closed guard on one of these refuses the session once it breaks.
# (11-15, the laptop: its check counts file edits and clicks as broad too, not only the shell.)
BROAD_TOOLS = ('Bash', 'Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'computer',
               r'mcp__claude-in-chrome__(computer|browser_batch)', r'mcp__computer-use__\w+', r'mcp__[\w-]+__(\*|\.\*)')


def broad(matcher):
    if matcher in ('', '*', '.*'):
        return True
    return any(re.fullmatch(t, part) for part in matcher.split('|') for t in BROAD_TOOLS)


def stale(rows, allow, today):
    """Allowlist entries that no longer hold anything back."""
    out = []
    names = {}
    for r in rows:
        script = script_of(r['command'], r['project']) if r.get('command') else None
        if script is not None:
            names.setdefault(script.name, []).append(r['state'])
    for name, entry in sorted(allow.items()):
        if entry.get('until') and dt.date.fromisoformat(entry['until']) < today:
            why = 'expired {}'.format(entry['until'])
        elif name not in names:
            why = 'names no registered hook'
        elif all(state == 'ok' for state in names[name]):
            why = 'the hook is wrapped now'
        else:
            continue
        out.append(dict(settings='allowlist', project=None, matcher='-', command='', state='STALE',
                        detail='{}: {}; delete the entry'.format(name, why)))
    return out


def check(settings, projects, allow, today=None, lib=LIB):
    today = today or dt.date.today()
    lib = Path(lib) if lib else None
    paths = [(p, None) for p in settings]
    paths += [(str(Path(d) / '.claude/settings.json'), str(d)) for d in projects]
    rows = []
    for row in registered(paths):
        state, detail = verdict(row, allow, today, lib)
        rows.append(dict(row, state=state, detail=detail))
    return rows + stale(rows, allow, today)


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
    ap.add_argument('settings', nargs='*')
    ap.add_argument('--project', action='append', default=[])
    ap.add_argument('--allow')
    ap.add_argument('--lib', default=str(LIB), help='the _hookfail.py every hook must import (default: '
                    "this checkout's rstack/hooks/_hookfail.py); --lib none skips the drift check")
    ap.add_argument('--json', action='store_true')
    a = ap.parse_args(argv)
    try:
        allow, extra = load_policy(a.allow or policy_path())
    except (ValueError, OSError) as exc:
        print('hook-wrap-check: policy file unusable: {}'.format(exc), file=sys.stderr)
        return 1
    settings = a.settings or [str(Path.home() / '.claude/settings.json')]
    projects = [str(Path(p).expanduser()) for p in a.project] + [p for p in extra if p not in a.project]
    rows = check(settings, [p for p in projects if (Path(p) / '.claude/settings.json').is_file()], allow,
                 lib=None if a.lib == 'none' else a.lib)
    bad = [r for r in rows if r['state'] in ('UNWRAPPED', 'MISSING', 'BROKEN', 'DRIFTED', 'BROAD_CLOSED', 'STALE')]
    if a.json:
        print(json.dumps(rows, indent=2))
    else:
        for r in rows:
            print('{:9}  [{}]  {}  {}'.format(r['state'], r['matcher'][:40], r['detail'],
                                               '' if r['state'] == 'ok' else '(' + r['settings'] + ')'))
        print('{} guard(s), {} not through the wrapper'.format(len(rows), len(bad)))
    return 1 if bad else 0


if __name__ == '__main__':
    sys.exit(main())
