#!/usr/bin/env python3
import json
import os
import shlex
import sys
from pathlib import Path
from brr.grok_runner import command
from brr.loom.runtime.port import wake_parts

room, core = sys.argv[1:]
def hook(event, timeout):
    return {"hooks": [{"type": "command", "command": shlex.quote(os.environ["BRNRD_JACK"]) + " --event " + event,
                       "timeout": timeout}]}
path = Path(room) / "self/.claude/settings.local.json"
path.parent.mkdir(parents=True, exist_ok=True)
# Grok finds project hooks only under the working tree, which here is the
# self's clone. Keep them out of any commit the body makes.
exclude = Path(room) / "self/.git/info/exclude"
if ".claude/" not in exclude.read_text().split():
    exclude.open("a").write(".claude/\n")
path.write_text(json.dumps({"hooks": {
    "SessionStart": [hook("start", 60)],
    "PreToolUse": [hook("pre", 60)],
    "PostToolUse": [hook("post", 60)],
    "Stop": [hook("stop", int(os.environ.get("BRNRD_STOP_TIMEOUT") or float(os.environ["BRNRD_WAIT"]) + 60))],
}}) + "\n")
# --rules is appended to Grok's own system prompt; the core rides there and
# the prompt file carries only the occasion.
core_text, _ = wake_parts(os.environ)
rules = "Follow the self's wake and the loom jack boundaries."
os.execvp("grok", command(Path(os.environ["BRNRD_OCCASION" if core_text else "BRNRD_WAKE"]),
                          model=core, rules=rules + "\n\n" + core_text if core_text else rules))
