#!/usr/bin/env python3
import json
import os
import subprocess
import shlex
import sys
from pathlib import Path
from brr.hooks import _render_vibe, _vibe_as_claude_tool, vibe_hooks_toml, PHASE_POST_TOOL, PHASE_PRE_TOOL, PHASE_STOP
from brr.vibe_runner import command, prepare_system_prompt
from brr.loom.runtime.port import wake_parts

# Native hooks use a different response schema. This folder translates the
# jack's Claude-shaped output; the loop and the jack stay shell-independent.
if sys.argv[1] == "hook":
    phase = sys.argv[2]
    event = {PHASE_PRE_TOOL: "pre", PHASE_POST_TOOL: "post", PHASE_STOP: "stop"}.get(phase)
    if event is None:
        raise SystemExit(0)
    payload = json.loads(sys.stdin.read() or "{}")
    result = subprocess.run(shlex.split(os.environ["BRNRD_JACK"]) + ["--event", event],
                            input=json.dumps(_vibe_as_claude_tool(payload)), text=True, capture_output=True)
    if result.stdout.strip():
        payload = json.loads(result.stdout)
        specific = payload.get("hookSpecificOutput", {})
        context = specific.get("additionalContext")
        block = payload.get("decision") == "block" or specific.get("permissionDecision") == "deny"
        reason = payload.get("reason") or specific.get("permissionDecisionReason")
        print(json.dumps(_render_vibe(phase, context, block, reason)))
    raise SystemExit(result.returncode)

room, core = sys.argv[1:]
room = Path(room)
env = dict(os.environ, VIBE_ACTIVE_MODEL=core)
# The self's core is the system prompt (identity alone when its recipe kept
# the core in the wake); the rest of the wake travels on stdin.
core_text, occasion = wake_parts(env)
prompt = prepare_system_prompt(Path(env["BRNRD_CORE"]) if core_text else room / "self/core/identity.md", env)
hooks = room / ".vibe/hooks.toml"
hooks.parent.mkdir(parents=True, exist_ok=True)
hooks.write_text(vibe_hooks_toml(
    shlex.join([sys.executable, str(Path(__file__).resolve())]),
    timeout=float(env.get("BRNRD_STOP_TIMEOUT") or float(env["BRNRD_WAIT"]) + 60),
))
try:
    result = subprocess.run(command(room), input=occasion,
                            text=True, env=env)
finally:
    prompt.unlink(missing_ok=True)
raise SystemExit(result.returncode)
