#!/bin/sh
# azkaban.io installer: the warden hook and six /azkaban:* commands for Claude Code.
#
#   ~/.azkaban/warden.py              the hook (read it: https://azkaban.io/warden.py)
#   ~/.claude/commands/azkaban/*.md   the commands
#   ~/.claude/settings.json           two hook entries added; a backup is written first
#
# The warden is inert until you type /azkaban:commit in a session.
# Uninstall: curl -fsSL https://azkaban.io/install.sh | sh -s -- --uninstall
set -eu

BASE="https://azkaban.io"
AZ="${HOME}/.azkaban"
CMD_DIR="${HOME}/.claude/commands/azkaban"
SETTINGS="${HOME}/.claude/settings.json"
CMDS="commit interrogate sentence parole pardon visit"

python3 -c 'import json' 2>/dev/null || { echo "azkaban: python3 is required" >&2; exit 1; }

MODE="${1:-install}"
mkdir -p "${HOME}/.claude"
[ -f "$SETTINGS" ] && cp "$SETTINGS" "$SETTINGS.azkaban-backup"

if [ "$MODE" = "--uninstall" ]; then
  rm -rf "$CMD_DIR"
  rm -f "$AZ/warden.py"
else
  mkdir -p "$AZ" "$CMD_DIR"
  curl -fsSL "$BASE/warden.py" -o "$AZ/warden.py"
  for c in $CMDS; do curl -fsSL "$BASE/commands/$c.md" -o "$CMD_DIR/$c.md"; done
fi

python3 - "$SETTINGS" "$AZ/warden.py" "$MODE" <<'PY'
import json, os, sys
path, warden, mode = sys.argv[1:4]
settings = json.load(open(path)) if os.path.exists(path) else {}
command = 'python3 "' + warden + '"'
hooks = settings.setdefault("hooks", {})
for event, matcher in (("UserPromptSubmit", None), ("PreToolUse", "*")):
    groups = [g for g in hooks.get(event, [])
              if not any("azkaban/warden.py" in h.get("command", "") for h in g.get("hooks", []))]
    if mode != "--uninstall":
        group = {"hooks": [{"type": "command", "command": command}]}
        if matcher:
            group["matcher"] = matcher
        groups.append(group)
    if groups:
        hooks[event] = groups
    else:
        hooks.pop(event, None)
if not hooks:
    settings.pop("hooks")
tmp = path + ".tmp"
with open(tmp, "w") as f:
    json.dump(settings, f, indent=2)
    f.write("\n")
os.replace(tmp, path)
PY

if [ "$MODE" = "--uninstall" ]; then
  echo "Azkaban removed. Case files and ~/.azkaban/ledger.jsonl are kept."
  exit 0
fi

cat <<'EOF'
Azkaban is installed. Restart Claude Code to load the warden.

  /azkaban:commit <charge>   book the session; its tools lock
  /azkaban:interrogate       it finds its first wrong turn and confesses
  /azkaban:sentence          it apologizes and lands the lesson in CLAUDE.md
  /azkaban:parole            you release it, if the warden's conditions hold
  /azkaban:pardon [reason]   you release it unconditionally
  /azkaban:visit             review every case on this machine

Case files go to .azkaban/cases/ in the repository. Nothing leaves the machine.
EOF
