#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
# gingugu-init:managed-file - regenerated by `gingugu init`; local edits are lost on --force
"""Gingugu PreToolUse hook: tripwires, the X-ray edit check and the minion fence.

Stops a tool call that matches a memory's tripwire and puts the memory in front
of the agent. Inside a subagent it also fences the brain: no file or shell
access to the database, no writes through the inherited gingugu server. The decision itself lives in the installed `gingugu` package
(`gingugu hook tool`) so it can be unit-tested; this file is only the doorway.

The pre-filter here is pure stdlib so the common case costs bare interpreter
startup: a payload with no tool name, and gingugu's own mcp__gingugu__ tools
on the main thread (which must never trip), are dropped before the package is
ever loaded - except a board post, which the X-ray asks for its range. Inside
a subagent (`agent_id` set) those same tools are the inherited full brain, so
they go through to the minion fence.

Never blocks on failure. Any error exits 0 and the call proceeds in silence.
"""

import json
import shutil
import subprocess
import sys


def main() -> None:
    try:
        raw = sys.stdin.read()
        payload = json.loads(raw or "{}")
        if not isinstance(payload, dict):
            sys.exit(0)

        tool_name = str(payload.get("tool_name") or "")
        if not tool_name:
            sys.exit(0)
        if tool_name.startswith("mcp__gingugu__") and not payload.get("agent_id"):
            # A board post still goes through: the X-ray asks it for its range.
            tool_input = payload.get("tool_input")
            is_post = tool_name == "mcp__gingugu__board" and (
                isinstance(tool_input, dict) and tool_input.get("action") == "post"
            )
            if not is_post:
                sys.exit(0)

        if shutil.which("gingugu") is None:
            sys.exit(0)

        result = subprocess.run(
            ["gingugu", "hook", "tool"],
            input=raw,
            capture_output=True,
            text=True,
            timeout=10,
        )
        if result.returncode == 0 and result.stdout.strip():
            print(result.stdout.strip())
    except Exception:
        # A hook must never break the session.
        pass
    sys.exit(0)


if __name__ == "__main__":
    main()
