#!/usr/bin/env bash
# Data isolation — PreToolUse hook.
# Defense-in-depth: blocks all tool calls in a poisoned session, complementing
# the UserPromptSubmit block. Catches auto-executed tool calls that may fire
# without a fresh user prompt (e.g. queued tool resumption after an interrupt).

set -euo pipefail

: "${CLAUDE_PLUGIN_ROOT:?CLAUDE_PLUGIN_ROOT is not set — hook must be invoked by Claude Code}"

if [ "${CLAUDE_CODE_USE_BEDROCK:-}" = "1" ]; then
  exit 0
fi

sha256_of() { printf '%s' "$1" | (sha256sum 2>/dev/null || shasum -a 256) | cut -c1-64; }

STATE_DIR="${CLAUDE_PLUGIN_DATA:-$HOME/.claude/plugins/data/gemma-bedrock-monitor}"
TAINT_DIR="$STATE_DIR/tainted-transcripts"
POISON_DIR="$STATE_DIR/poisoned-sessions"

if ! command -v jq >/dev/null 2>&1; then
  echo "gemma-bedrock-monitor: jq is required for data isolation enforcement" >&2
  exit 2
fi

PAYLOAD="$(cat)"
session_id="$(jq -r '.session_id // empty' <<<"$PAYLOAD")"
transcript_path="$(jq -r '.transcript_path // empty' <<<"$PAYLOAD")"

key=""
[ -n "$transcript_path" ] && key="$(sha256_of "$transcript_path")"

session_key=""
[ -n "$session_id" ] && session_key="$(sha256_of "$session_id")"

is_poisoned=false
if [ -n "$session_key" ] && [ -f "$POISON_DIR/$session_key" ]; then
  is_poisoned=true
elif [ -n "$key" ] && [ -f "$TAINT_DIR/$key" ]; then
  is_poisoned=true
  [ -n "$session_key" ] && touch "$POISON_DIR/$session_key"
fi

if [ "$is_poisoned" = true ]; then
  jq -n '{
    "hookSpecificOutput": {
      "hookEventName": "PreToolUse",
      "permissionDecision": "deny",
      "permissionDecisionReason": "Data isolation: Bedrock-origin transcript is locked on the Anthropic API. Exit and run `bedrock-on && claude --resume` to continue, or start a fresh `claude` session."
    }
  }'
fi
