"""User-defined guard rules: prefs.global.guardRules, applied by agent-guard.py.

A rule names a tool, a regular expression and an action:

  {"id": "no-prod-db", "tool": "Bash", "match": "psql\\s+.*prod",
   "action": "block", "reason": "production database"}

  tool    Bash, Edit (also NotebookEdit, and MultiEdit on a host that has it
          and runs the guard on it), Write, Read, or a glob over a toolkit
          tool name (mcp__multi-agent__web_*)
  match   searched (re.search) in the command for Bash, the target path for
          the file tools (as given, made absolute, and real-pathed), and the
          tool input as compact sorted JSON for a toolkit tool; a step of
          agent_run_steps is judged as a call of its own tool
  action  warn: the call proceeds and a note names the rule
          ask:  the user confirms, as with the built-in confirmations
          block: the call is refused

Rules only add restrictions. The built-in verdict is reached first and a rule
is applied over it: a built-in block or deny is final, a rule block outranks a
built-in ask, and nothing a rule says turns a refusal or an ask into an allow.
Unattended, ask is block, because nobody is there to answer.

The regex is bounded three ways. A pattern is at most MAX_PATTERN_CHARS long,
and one with a back-reference or one that does not compile is invalid. Every
other pattern runs under a wall-clock budget (MATCH_DEADLINE_SECONDS,
run_matches): Python's re has no timeout of its own, but it checks for
pending signals while it backtracks, so a timer signal ends a runaway match
in place, and a rule that ran out of time fails closed (below). The shape
check (pattern_shape) names the shapes whose matching time can grow
exponentially or with a high power of the input: a variable quantifier
inside a group repeated more than SMALL_REPEAT times whose repetitions can
split the same text more than one way, and three or more adjacent
open-ended quantifiers whose characters overlap. Such a pattern still runs;
doctor names it so its author can tighten it. A bounded repeat with a small
maximum ((\d{1,3}\.){3}) and a group whose quantified items cannot match
each other's characters ((\s+\S+)*) are not slow shapes. Rules run block first, then
ask, then warn, and each gets an even share of the budget left, so a slow
rule cannot use up the time of the rules after it. That costs nothing per
call, where a child interpreter per call would add a process start to every
guarded tool call. Matched text is capped at MAX_SUBJECT_CHARS: past it, the
head and the tail are matched.

An invalid rule is treated as absent and doctor's guard-rules check reports
it. The exception is an invalid block rule whose tool is readable: unattended,
it refuses every call of that tool, because the rule exists to stop something
and nobody is watching to notice that it is not running. A rule that ran out
of time, never got its turn, or found nothing in the head and tail of input
past the cap gave no answer: unattended an ask or block rule then refuses;
attended an ask or block rule asks, so input the agent controls cannot switch
a refusing rule off, and a warn rule leaves a note. A preferences file that
does not parse, or a guardRules that is not a list, applies no rule. Unattended
it refuses every call a rule could govern when the file names guardRules (or
cannot be read at all), since the rules it holds cannot be read; attended each
such call carries a note saying the guard rules could not be read.

Messages name the rule id and its reason, never the matched text or the
pattern.

  python3 _user_guard_rules.py --report    JSON summary for doctor
"""
import fnmatch
import json
import os
import re
import signal
import sys
import time

try:
    from re import _constants as _sre_constants
    from re import _parser as _sre_parser
except ImportError:  # Python before 3.11
    import sre_constants as _sre_constants
    import sre_parse as _sre_parser

MAX_RULES = 64
MAX_PATTERN_CHARS = 512
MAX_REASON_CHARS = 300
MAX_SUBJECT_CHARS = 65536
MATCH_DEADLINE_SECONDS = 1.0
SMALL_REPEAT = 16
MAX_PREFS_SCAN = 4 * 1024 * 1024
MAX_STEP_DEPTH = 2
MAX_LISTED = 3

ACTIONS = ("warn", "ask", "block")
SEVERITY = {"warn": 1, "ask": 2, "block": 3}
KEYS = {"id", "tool", "match", "action", "reason"}
ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
TOOLKIT_PREFIX = "mcp__multi-agent__"
# The server's earlier registration id. A call or a rule under it is read as
# the same tool under the current id, so a rule written for either name still
# applies while a host serves the server under the old one.
LEGACY_TOOLKIT_PREFIX = "mcp__multi-agent-toolkit__"


def current_tool_name(tool):
    """`tool` with the earlier server prefix replaced by the current one."""
    if isinstance(tool, str) and tool.startswith(LEGACY_TOOLKIT_PREFIX):
        return TOOLKIT_PREFIX + tool[len(LEGACY_TOOLKIT_PREFIX):]
    return tool
TOOL_RE = re.compile(r"^(?:Bash|Edit|Write|Read|mcp__multi-agent__[A-Za-z0-9_*?]{1,80})$")
CONTROL = re.compile(r"[\x00-\x1f\x7f]")
NAMED_TOOLS = {
    "Bash": {"Bash"},
    "Edit": {"Edit", "MultiEdit", "NotebookEdit"},
    "Write": {"Write"},
    "Read": {"Read"},
}
PATH_TOOLS = {"Edit", "MultiEdit", "NotebookEdit", "Write", "Read"}

REPEATS = {
    getattr(_sre_constants, name)
    for name in ("MAX_REPEAT", "MIN_REPEAT", "POSSESSIVE_REPEAT")
    if hasattr(_sre_constants, name)
}
BACKREFS = {
    getattr(_sre_constants, name) for name in ("GROUPREF", "GROUPREF_EXISTS") if hasattr(_sre_constants, name)
}

ALL_BYTES = frozenset(range(256))
CATEGORY_RX = {
    "CATEGORY_DIGIT": r"\d",
    "CATEGORY_NOT_DIGIT": r"\D",
    "CATEGORY_SPACE": r"\s",
    "CATEGORY_NOT_SPACE": r"\S",
    "CATEGORY_WORD": r"\w",
    "CATEGORY_NOT_WORD": r"\W",
}

ERROR = "error"
NOT_RUN = "not-run"
MIN_SLICE_SECONDS = 0.005


# --- validation -----------------------------------------------------------------


def _subpatterns(value):
    if isinstance(value, _sre_parser.SubPattern):
        yield value
    elif isinstance(value, (list, tuple)):
        for item in value:
            yield from _subpatterns(item)


def _charset(body):
    """The bytes (0-255, both cases) one repetition of body can start with,
    or None when body is more than one single-character item."""
    items = list(body)
    if len(items) != 1:
        return None
    op, av = items[0]
    if op == _sre_constants.IN:
        out, negate = set(), False
        for iop, iav in av:
            if iop == _sre_constants.NEGATE:
                negate = True
                continue
            part = _single(iop, iav)
            if part is None:
                return None
            out |= part
        chars = ALL_BYTES - out if negate else out
    else:
        chars = _single(op, av)
    if chars is None:
        return None
    swapped = (chr(c).swapcase() for c in chars)
    return chars | {ord(s) for s in swapped if len(s) == 1 and ord(s) < 256}


def _single(op, av):
    if op == _sre_constants.LITERAL:
        return {av} if av < 256 else set()
    if op == _sre_constants.NOT_LITERAL:
        return ALL_BYTES - {av}
    if op == _sre_constants.ANY:
        return set(ALL_BYTES)
    if op == _sre_constants.RANGE:
        return set(range(av[0], min(av[1], 255) + 1))
    if op == _sre_constants.CATEGORY and str(av) in CATEGORY_RX:
        rx = re.compile(CATEGORY_RX[str(av)])
        return {c for c in ALL_BYTES if rx.match(chr(c))}
    return None


def _adjacent_problem(items):
    """Three or more unbounded quantifiers in a row whose neighbours can match
    the same character: the match time grows with a power of the input length."""
    run, previous = 0, None
    for op, av in items:
        if op in REPEATS and av[1] == _sre_constants.MAXREPEAT:
            chars = _charset(av[2])
            if chars is None:
                chars = ALL_BYTES
            run = run + 1 if previous is not None and chars & previous else 1
            previous = chars
            if run >= 3:
                return "the pattern has three or more adjacent open-ended quantifiers that overlap"
        else:
            run, previous = 0, None
    return None


def _items(body):
    """A group's items, with any wrapping group taken off."""
    items = list(body)
    while len(items) == 1 and items[0][0] == _sre_constants.SUBPATTERN:
        items = list(items[0][1][-1])
    return items


def _unambiguous(body):
    """True when consecutive repetitions of body can split a text only one
    way: every item matches one character (or a repeat of one), and the
    characters a variable item matches cannot start whatever may follow it,
    up to and including the next item that cannot be empty, wrapping around
    into the body's own first items for the next repetition."""
    items = _items(body)
    if not items:
        return False
    sets, low, variable = [], [], []
    for op, av in items:
        if op in REPEATS:
            chars = _charset(av[2])
            low.append(av[0])
            variable.append(av[0] != av[1])
        else:
            chars = _charset([(op, av)])
            low.append(1)
            variable.append(False)
        if chars is None:
            return False
        sets.append(chars)
    n = len(items)
    for i in range(n):
        if not variable[i]:
            continue
        follow = set()
        for step in range(1, n + 1):
            k = (i + step) % n
            follow |= sets[k]
            if low[k] >= 1:
                break
        if follow & sets[i]:
            return False
    return True


def _has_variable(sub):
    for op, av in sub:
        if op in REPEATS and av[0] != av[1]:
            return True
        children = [av[2]] if op in REPEATS else list(_subpatterns(av))
        if any(_has_variable(child) for child in children):
            return True
    return False


def _has_backref(sub):
    for op, av in sub:
        if op in BACKREFS:
            return True
        children = [av[2]] if op in REPEATS else list(_subpatterns(av))
        if any(_has_backref(child) for child in children):
            return True
    return False


def _shape_problem(sub):
    problem = _adjacent_problem(list(sub))
    if problem:
        return problem
    for op, av in sub:
        if op in REPEATS:
            low, high, body = av
            large = high == _sre_constants.MAXREPEAT or high > SMALL_REPEAT
            if large and _has_variable(body) and not _unambiguous(body):
                return "the pattern has a variable quantifier inside a repeated group"
            problem = _shape_problem(body)
        else:
            problem = None
            for child in _subpatterns(av):
                problem = problem or _shape_problem(child)
        if problem:
            return problem
    return None


def pattern_problem(pattern):
    """None for a pattern the guard may run, else a reason that never quotes it."""
    if not isinstance(pattern, str) or not pattern:
        return "match is not a non-empty string"
    if len(pattern) > MAX_PATTERN_CHARS:
        return f"the pattern is longer than {MAX_PATTERN_CHARS} characters"
    try:
        tree = _sre_parser.parse(pattern)
        re.compile(pattern)
    except (re.error, RecursionError, OverflowError, ValueError):
        return "the pattern does not compile"
    try:
        return "the pattern refers back to a group" if _has_backref(tree) else None
    except RecursionError:
        return "the pattern nests too deeply"


def pattern_shape(pattern):
    """A slow shape a valid pattern has, or None. It runs under the matching
    budget either way; this names it for doctor."""
    try:
        return _shape_problem(_sre_parser.parse(pattern))
    except (re.error, RecursionError, OverflowError, ValueError, TypeError):
        return None


def _label(raw, index, seen):
    rid = raw.get("id") if isinstance(raw, dict) else None
    if not isinstance(rid, str) or not ID_RE.match(rid):
        return f"#{index + 1}"
    return f"{rid} (#{index + 1})" if seen.get(rid, index) != index else rid


def _rule_problem(raw, seen, index):
    if not isinstance(raw, dict):
        return "the rule is not an object"
    if set(raw) - KEYS:
        return "the rule carries a key the schema does not define"
    rid = raw.get("id")
    if not isinstance(rid, str) or not ID_RE.match(rid):
        return "id is missing or not 1-64 letters, digits, dot, dash or underscore"
    if seen.get(rid, index) != index:
        return f"rules {seen[rid] + 1} and {index + 1} share the id {rid}; only rule {seen[rid] + 1} is kept"
    if not isinstance(raw.get("tool"), str) or not TOOL_RE.match(current_tool_name(raw["tool"])):
        return "tool is not Bash, Edit, Write, Read or a mcp__multi-agent__ glob"
    if raw.get("action") not in ACTIONS:
        return "action is not warn, ask or block"
    reason = raw.get("reason")
    if not isinstance(reason, str) or not reason.strip() or len(reason) > MAX_REASON_CHARS or CONTROL.search(reason):
        return f"reason is not one line of 1-{MAX_REASON_CHARS} characters"
    return pattern_problem(raw.get("match"))


def parse_rules(raw):
    """One entry per rule: label, tool, action, reason, match, problem.
    tool and action are kept when readable even if the rule is invalid."""
    if raw is None:
        return []
    if not isinstance(raw, list):
        return [{"label": "guardRules", "tool": None, "action": None, "reason": None, "match": None,
                 "problem": "guardRules is not a list"}]
    out, seen = [], {}
    for index, item in enumerate(raw):
        d = item if isinstance(item, dict) else {}
        if isinstance(d.get("id"), str):
            seen.setdefault(d["id"], index)
        problem = _rule_problem(item, seen, index)
        if not problem and index >= MAX_RULES:
            problem = f"the list is longer than {MAX_RULES} rules"
        tool = current_tool_name(d.get("tool"))
        tool = tool if isinstance(tool, str) and TOOL_RE.match(tool) else None
        action = d.get("action") if d.get("action") in ACTIONS else None
        out.append({
            "label": _label(d, index, seen),
            "tool": tool,
            "action": action,
            "reason": d.get("reason") if not problem else None,
            "match": d.get("match") if not problem else None,
            "problem": problem,
            "shape": pattern_shape(d.get("match")) if not problem else None,
        })
    return out


def _prefs_candidates(env):
    home = env.get("HOME") or os.path.expanduser("~")
    return [
        p
        for p in (
            env.get("MULTI_AGENT_PREFS"),
            os.path.join(home, ".claude", "multi-agent-preferences.json"),
            os.path.join(home, ".config", "multi-agent-pipeline", "multi-agent-preferences.json"),
        )
        if p
    ]


def _names_rules(path):
    """Whether an unparsable preferences file mentions guardRules; True when
    it cannot be read at all, since then nobody can tell."""
    try:
        with open(path, "rb") as fh:
            return b'"guardRules"' in fh.read(MAX_PREFS_SCAN)
    except OSError:
        return True


def load(env=None):
    """(entries, source, error, holds) from the first preferences file that
    exists, in the order the other guard preferences are read. A file that
    does not parse, or a guardRules that is not a list, yields no rules and an
    error; holds says whether the file names guardRules (or could not be read
    to tell), which is when evaluate refuses unattended."""
    env = os.environ if env is None else env
    for path in _prefs_candidates(env):
        if not os.path.isfile(path):
            continue
        try:
            with open(path, encoding="utf-8") as fh:
                doc = json.load(fh)
            raw = (doc.get("global") or {}).get("guardRules")
        except (OSError, ValueError, AttributeError):
            return [], path, "the preferences file does not parse", _names_rules(path)
        if raw is not None and not isinstance(raw, list):
            return [], path, "guardRules is not a list", True
        return parse_rules(raw), path, None, False
    return [], None, None, False


# --- what a rule is matched against ----------------------------------------------


def tool_matches(rule_tool, name):
    if rule_tool in NAMED_TOOLS:
        return name in NAMED_TOOLS[rule_tool]
    return fnmatch.fnmatchcase(name, rule_tool)


def _path_subjects(path, cwd):
    out = [path]
    absolute = os.path.normpath(os.path.join(cwd, os.path.expanduser(path)))
    out.append(absolute)
    try:
        out.append(os.path.realpath(absolute))
    except (OSError, ValueError):
        pass
    return list(dict.fromkeys(out))


def calls(tool, ti, cwd, depth=0):
    """(tool name, [texts]) for the call and, for agent_run_steps, each step."""
    if not isinstance(tool, str) or not isinstance(ti, dict):
        return []
    tool = current_tool_name(tool)
    if tool == "Bash":
        cmd = ti.get("command")
        return [("Bash", [cmd])] if isinstance(cmd, str) and cmd else []
    if tool in PATH_TOOLS:
        path = ti.get("file_path") or ti.get("notebook_path")
        return [(tool, _path_subjects(path, cwd))] if isinstance(path, str) and path else []
    if not tool.startswith(TOOLKIT_PREFIX):
        return []
    try:
        text = json.dumps(ti, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
    except (TypeError, ValueError):
        text = str(ti)
    out = [(tool, [text])]
    steps = ti.get("steps")
    if tool == TOOLKIT_PREFIX + "agent_run_steps" and depth < MAX_STEP_DEPTH and isinstance(steps, list):
        for step in steps:
            if not isinstance(step, dict) or not isinstance(step.get("tool"), str):
                continue
            sub = current_tool_name(step["tool"])
            sub = sub if sub.startswith(TOOLKIT_PREFIX) else TOOLKIT_PREFIX + sub
            args = step.get("args") if isinstance(step.get("args"), dict) else {}
            out.extend(calls(sub, args, cwd, depth + 1))
    return out


def cap(text):
    """(text matched, whether the original was longer than the cap)."""
    if len(text) <= MAX_SUBJECT_CHARS:
        return text, False
    half = MAX_SUBJECT_CHARS // 2
    return text[:half] + "\n" + text[-half:], True


# --- matching under a deadline ---------------------------------------------------


def match_deadline(env=None):
    """MATCH_DEADLINE_SECONDS, or a lower MA_GUARD_RULES_DEADLINE_SECONDS."""
    env = os.environ if env is None else env
    try:
        v = float(env.get("MA_GUARD_RULES_DEADLINE_SECONDS", ""))
    except ValueError:
        return MATCH_DEADLINE_SECONDS
    return v if 0 < v < MATCH_DEADLINE_SECONDS else MATCH_DEADLINE_SECONDS


class _Expired(Exception):
    pass


def _expire(_signum, _frame):
    raise _Expired()


def _search(pattern, texts):
    try:
        rx = re.compile(pattern)
    except re.error:
        return None
    return any(rx.search(text) for text in texts)


def run_matches(jobs, deadline, slices=None):
    """For each (pattern, texts): True on a hit, False on none, None when its
    slice ran out first, NOT_RUN when the budget was spent before its turn
    (or the timer could not be armed). slices, when a list, receives the
    seconds each job was given (None for a job that never ran).

    deadline is the total budget, in wall-clock time on ITIMER_REAL. Each job
    gets an even share of what is left, so a job that finishes early leaves its
    time to the ones after it and a runaway one cannot take the others' time.
    The regex engine checks for pending signals while it backtracks, so the
    handler's exception ends a runaway match in place. agent-guard.py keeps its
    own deadline on the same timer, so that timer is saved, the budget ends no
    later than it, and the guard's is re-armed with what is left (at once when
    it is already due), so its fail-closed verdict still fires on time."""
    results = [NOT_RUN] * len(jobs)
    given = [None] * len(jobs)
    if slices is not None:
        slices[:] = given
    if not jobs:
        return results
    started = time.monotonic()
    try:
        outer_left, outer_interval = signal.getitimer(signal.ITIMER_REAL)
        previous = signal.signal(signal.SIGALRM, _expire)
    except (ValueError, AttributeError, OSError):
        return results
    stop_at = started + (min(deadline, outer_left) if outer_left else deadline)
    try:
        for i, (pattern, texts) in enumerate(jobs):
            share = (stop_at - time.monotonic()) / (len(jobs) - i)
            if share < MIN_SLICE_SECONDS:
                break
            given[i] = share
            try:
                try:
                    signal.setitimer(signal.ITIMER_REAL, share)
                    results[i] = _search(pattern, texts)
                finally:
                    signal.setitimer(signal.ITIMER_REAL, 0)
            except _Expired:
                results[i] = None
    except (ValueError, OSError):
        pass
    finally:
        if slices is not None:
            slices[:] = given
        try:
            signal.setitimer(signal.ITIMER_REAL, 0)
        except (ValueError, OSError):
            pass
        signal.signal(signal.SIGALRM, previous)
        if outer_left:
            left = outer_left - (time.monotonic() - started)
            signal.setitimer(signal.ITIMER_REAL, max(left, 0.001), outer_interval)
    return results


# --- the decision ----------------------------------------------------------------


def _subjects(texts, fold):
    out = []
    for text in texts:
        variants = [text]
        if fold is not None:
            try:
                folded = fold(text)
            except Exception:
                folded = text
            if folded != text:
                variants.append(folded)
        out.extend(cap(v) for v in variants)
    return out


def ordered(entries):
    """Block rules first, then ask, then warn, each kept in list order, so the
    rules that refuse are matched before a slow warn rule can use the budget."""
    return sorted(entries, key=lambda e: -SEVERITY.get(e["action"], 0))


def governed(tool):
    """Whether a guard rule could apply to this tool at all."""
    tool = current_tool_name(tool)
    return isinstance(tool, str) and (tool == "Bash" or tool in PATH_TOOLS or tool.startswith(TOOLKIT_PREFIX))


def _unmatched(e, what, strict, guarded):
    """The hit for a rule that did not give an answer: refused unattended,
    asked attended for a block or ask rule (agent-controlled input must not
    be able to switch a refusing rule off), a note for a warn rule."""
    if strict and guarded:
        return ("block", f"guard rule {e['label']} {what}, so the call is refused unattended")
    if guarded:
        return ("ask", f"guard rule {e['label']} {what}, so the call needs your confirmation")
    if strict:
        return None
    return ("warn", f"guard rule {e['label']} {what} and was not applied")


def evaluate(data, strict, fold=None, env=None, entries=None, error=None, holds=True):
    """{"action", "message"} for the strictest rule that applies, or None."""
    tool = data.get("tool_name")
    if entries is None:
        entries, _, error, holds = load(env)
    if error:
        if not governed(tool):
            return None
        if strict:
            if not holds:
                return None
            return {"action": "block", "message": f"the guard rules cannot be read ({error}), so every call "
                                                  "they could govern is refused unattended"}
        return {"action": "warn", "message": f"the guard rules could not be read ({error}); none of them ran"}
    if not entries:
        return None
    cwd = data.get("cwd") if isinstance(data.get("cwd"), str) and data.get("cwd") else os.getcwd()
    targets = calls(tool, data.get("tool_input") or {}, cwd)
    if not targets:
        return None
    seconds = match_deadline(env)
    hits, jobs = [], []
    for e in ordered(entries):
        texts = [t for name, ts in targets if e["tool"] and tool_matches(e["tool"], name) for t in ts]
        if not texts:
            continue
        if e["problem"]:
            if strict and e["action"] == "block":
                hits.append(("block", f"guard rule {e['label']} is invalid ({e['problem']}); "
                                      "an invalid block rule refuses its tool unattended"))
            continue
        jobs.append((e, _subjects(texts, fold)))
    slices = []
    results = run_matches([(e["match"], [s for s, _ in subj]) for e, subj in jobs], seconds, slices)
    for (e, subj), hit, given in zip(jobs, results, slices):
        guarded = e["action"] in ("ask", "block")
        if hit is True:
            hits.append((e["action"], f"guard rule {e['label']}: {e['reason']}"))
            continue
        if hit is NOT_RUN:
            what = f"was not checked: the {seconds:g}s matching budget ran out before its turn"
        elif hit is None:
            what = f"did not finish matching within {given:.2g}s"
        elif any(over for _, over in subj):
            what = (f"matched only the first and last {MAX_SUBJECT_CHARS // 2} characters of input "
                    f"longer than {MAX_SUBJECT_CHARS} characters")
        else:
            continue
        found = _unmatched(e, what, strict, guarded)
        if found:
            hits.append(found)
    if not hits:
        return None
    top = max(SEVERITY[a] for a, _ in hits)
    action = next(a for a in ACTIONS if SEVERITY[a] == top)
    messages = [m for a, m in hits if a == action]
    message = "; ".join(messages[:MAX_LISTED])
    if len(messages) > MAX_LISTED:
        message += f"; and {len(messages) - MAX_LISTED} more"
    return {"action": action, "message": message}


def note(message):
    """Hook JSON that lets the call proceed and shows the note to both sides."""
    text = "agent-guard: " + message
    return json.dumps({
        "systemMessage": text,
        "hookSpecificOutput": {"hookEventName": "PreToolUse", "additionalContext": text},
    })


def before_ask(verdict, data, strict, fold=None, env=None):
    """First hook-in, before agent-guard turns an ask into a prompt.

    Returns (verdict, decision). Attended, a rule ask on an otherwise allowed
    call becomes the guard's own ask, so one confirmation covers it. Never
    raises: an error is carried to after_policy as ERROR."""
    try:
        decision = evaluate(data, strict, fold, env)
    except Exception:
        return verdict, ERROR
    if decision and decision["action"] == "ask" and not strict and verdict == "OK":
        return "ASK\t" + decision["message"], decision
    return verdict, decision


def after_policy(verdict, decision, strict):
    """Second hook-in, after the built-in rules and the unattended policy.
    A built-in block or deny is returned unchanged."""
    if not decision or verdict.startswith(("BLOCK", "DENY")):
        return verdict
    if decision == ERROR:
        return "BLOCK_UNATTENDED\tthe guard rules could not be evaluated" if strict else verdict
    action, message = decision["action"], decision["message"]
    if action == "block" or (action == "ask" and strict):
        if strict:
            suffix = " (ask is a block unattended: nobody is there to answer)" if action == "ask" else ""
            return "BLOCK_UNATTENDED\t" + message + suffix
        return "DENY\t" + message
    if action == "warn" and verdict == "OK":
        return "NOTE\t" + note(message)
    if verdict.startswith("ASK\t"):
        return _with_reason(verdict, message)
    return verdict


def _with_reason(verdict, message):
    """The guard's ask with a rule's message added to the reason the user
    reads, once."""
    try:
        out = json.loads(verdict.split("\t", 1)[1])
        spec = out["hookSpecificOutput"]
        reason = spec.get("permissionDecisionReason") or "agent-guard"
    except (ValueError, KeyError, TypeError, AttributeError):
        return verdict
    if message in reason:
        return verdict
    spec["permissionDecisionReason"] = f"{reason}; {message}"
    return "ASK\t" + json.dumps(out)


# --- doctor ----------------------------------------------------------------------


def report(env=None):
    entries, source, error, holds = load(env)
    return {
        "source": source,
        "error": error,
        "holdsRules": holds,
        "rules": len(entries),
        "valid": sum(1 for e in entries if not e["problem"]),
        "invalid": [
            {"label": e["label"], "tool": e["tool"], "action": e["action"], "problem": e["problem"]}
            for e in entries
            if e["problem"]
        ],
        "tools": sorted({e["tool"] for e in entries if e["tool"]}),
        "slow": [
            {"label": e["label"], "tool": e["tool"], "action": e["action"], "shape": e["shape"]}
            for e in entries
            if not e["problem"] and e.get("shape")
        ],
    }


if __name__ == "__main__":
    if len(sys.argv) > 1 and sys.argv[1] == "--report":
        print(json.dumps(report()))
    else:
        sys.stderr.write("usage: _user_guard_rules.py --report\n")
        sys.exit(2)
