#!/usr/bin/env bash
# Data isolation — UserPromptSubmit hook.
# Blocks any prompt in a session that resumed a Bedrock-tainted transcript on
# the Anthropic API. The block decision prevents the prompt from being appended
# to the message list and stops the HTTP POST to the Anthropic API entirely.

set -euo pipefail

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

# Never block Bedrock sessions.
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")"

# Two-layer check:
# 1. Poison flag — written by SessionStart this run (fast path).
# 2. Live taint check — defends against /resume used mid-session (which may not
#    fire a fresh SessionStart), and any race where SessionStart ran after the
#    first prompt was already queued.
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
  # Back-fill the poison flag so subsequent checks are fast.
  [ -n "$session_key" ] && touch "$POISON_DIR/$session_key"
fi

if [ "$is_poisoned" = true ]; then
  jq -n '{
    "decision": "block",
    "reason": "Data isolation: this transcript was previously active on AWS Bedrock and may contain client data. Sending it through the Anthropic API is blocked.\n\nTo continue this conversation:\n  1. Exit this session\n  2. Run: bedrock-on\n  3. Run: claude --resume\n\nTo start a fresh Anthropic API session, run `claude` without --resume."
  }'
fi
