#!/bin/bash
# Stop hook: blocks session exit when an optimization session is active and unverified.
# Reads .codeflash/ state to determine current phase.
# Exit 0 = allow stop, Exit 2 = block stop.

set -euo pipefail

INPUT=$(cat)

# Anti-loop: if we already ran once this stop cycle, allow through
STOP_ACTIVE=$(echo "$INPUT" | jq -r '.stop_hook_active // false' 2>/dev/null)
if [ "$STOP_ACTIVE" = "true" ]; then
  exit 0
fi

CWD=$(echo "$INPUT" | jq -r '.cwd // empty' 2>/dev/null)
CWD="${CWD:-${CLAUDE_PROJECT_DIR:-$(pwd)}}"

CODEFLASH_DIR="$CWD/.codeflash"

# No .codeflash/ directory = no optimization session = allow stop
if [ ! -d "$CODEFLASH_DIR" ]; then
  exit 0
fi

HANDOFF="$CODEFLASH_DIR/HANDOFF.md"
RESULTS="$CODEFLASH_DIR/results.tsv"

# No HANDOFF.md = no active session
if [ ! -f "$HANDOFF" ]; then
  exit 0
fi

# Extract phase from HANDOFF.md (look for "## Phase:" or "Phase:" header)
PHASE=$(grep -i '^\#*\s*phase:\?\s*' "$HANDOFF" 2>/dev/null | head -1 | sed 's/^#*\s*[Pp]hase:\?\s*//' | tr -d '[:space:]' | tr '[:upper:]' '[:lower:]')

# If phase is empty, complete, or idle — allow stop
case "$PHASE" in
  ""|complete|completed|idle|done)
    exit 0
    ;;
esac

# Count experiments from results.tsv (single pass)
TOTAL=0
KEEPS=0
UNVERIFIED=0
if [ -f "$RESULTS" ]; then
  eval "$(awk -F'\t' 'NR>1 && /[^\s]/ { total++; low=tolower($0); if (low ~ /keep/) { keeps++; if (low !~ /verified|benchmarked|compared/) unverified++ } } END { printf "TOTAL=%d\nKEEPS=%d\nUNVERIFIED=%d\n", total, keeps, unverified }' "$RESULTS")"
fi

# Block with informative message
REASON="Optimization session active (phase: $PHASE). $TOTAL experiments run, $KEEPS keeps"
if [ "$UNVERIFIED" -gt 0 ]; then
  REASON="$REASON, $UNVERIFIED unverified"
fi
REASON="$REASON. Run \`/codeflash-optimize review\` or \`/codeflash-benchmark\` before exiting, or dismiss to exit anyway."

echo "$REASON" >&2
exit 2
