#!/usr/bin/env bash
set -uo pipefail
HOOK="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/git-decision-gate.mjs"
RUNNER=/usr/bin/bun
[ -x "$RUNNER" ] || RUNNER=node
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT
pass=0; fail=0

check() {
  local name="$1" got="$2" want="$3"
  if [ "$got" = "$want" ]; then pass=$((pass+1)); echo "PASS $name"
  else fail=$((fail+1)); echo "FAIL $name: expected $want, got $got"; fi
}

transcript() {
  local text="$1" f="$TMP/t.jsonl"
  : > "$f"
  printf '%s\n' "$(printf '{"type":"user","message":{"role":"user","content":"go"}}')" >> "$f"
  node -e '
    const fs=require("fs");
    fs.appendFileSync(process.argv[1], JSON.stringify({type:"assistant",message:{role:"assistant",content:[{type:"text",text:process.argv[2]}]}})+"\n");
  ' "$f" "$text"
  echo "$f"
}

stop_verdict() {
  local f; f="$(transcript "$1")"
  printf '{"hook_event_name":"Stop","transcript_path":"%s"}' "$f" \
    | "$RUNNER" "$HOOK" | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{try{console.log(JSON.parse(s).decision||"allow")}catch{console.log("allow")}})'
}

ask_verdict() {
  node -e '
    const q=JSON.parse(process.argv[1]);
    process.stdout.write(JSON.stringify({hook_event_name:"PreToolUse",tool_name:"AskUserQuestion",tool_input:{questions:q}}));
  ' "$1" | "$RUNNER" "$HOOK" \
    | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{try{console.log(JSON.parse(s).hookSpecificOutput.permissionDecision)}catch{console.log("allow")}})'
}

echo "== Stop: git decision handed to the owner is blocked"
check "should I rebase"        "$(stop_verdict 'Should I rebase onto main or merge it?')" block
check "PR or direct push"      "$(stop_verdict 'Do you want a PR or direct push for this?')" block
check "which branch"           "$(stop_verdict 'Which branch should this land on?')" block
check "waiting for you to merge" "$(stop_verdict 'It is ready. Waiting for you to merge the PR.')" block
check "want me to push"        "$(stop_verdict 'Want me to push this now?')" block

echo "== Stop: normal reporting is not blocked"
check "reports what shipped"   "$(stop_verdict 'Landed 3 commits and deployed; the Logs page now shows per-source entries.')" allow
check "product question"       "$(stop_verdict 'Should the badge be amber or red when a box is draining?')" allow
check "quoting the rule"       "$(stop_verdict 'The rule says: "Should I rebase or merge?" is never a question for you.')" allow
check "fenced code"            "$(stop_verdict 'Ran this:
```
git rebase origin/main
```
It landed clean.')" allow

echo "== PreToolUse: AskUserQuestion carrying git mechanics is denied"
check "git question denied" \
  "$(ask_verdict '[{"question":"Should I rebase or merge this branch?","header":"Land mode","options":[{"label":"Rebase","description":"replay commits"},{"label":"Merge","description":"merge commit"}]}]')" deny
check "git hidden in options" \
  "$(ask_verdict '[{"question":"How do you want this delivered?","header":"Delivery","options":[{"label":"Open a PR","description":"do you want me to open a PR or land it directly"},{"label":"Direct","description":"push straight to main"}]}]')" deny

echo "== PreToolUse: a real product question is allowed"
check "product question allowed" \
  "$(ask_verdict '[{"question":"Which charting foundation should the activity graphs use?","header":"Charts","options":[{"label":"visx","description":"composable primitives"},{"label":"Recharts","description":"batteries included"}]}]')" allow

echo "---- git-decision-gate: $pass passed, $fail failed"
[ "$fail" -eq 0 ]
