#!/bin/bash
# PreCompact hook: serialize optimization state before context compaction.
# Writes .codeflash/.compact-state.json with critical session info.

set -euo pipefail

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

CODEFLASH_DIR="$CWD/.codeflash"

# Nothing to preserve if no .codeflash/ directory
if [ ! -d "$CODEFLASH_DIR" ]; then
  exit 0
fi

HANDOFF="$CODEFLASH_DIR/HANDOFF.md"
RESULTS="$CODEFLASH_DIR/results.tsv"
SETUP="$CODEFLASH_DIR/setup.md"
STATE_FILE="$CODEFLASH_DIR/.compact-state.json"

# Extract phase from HANDOFF.md
PHASE=""
NEXT_TARGET=""
if [ -f "$HANDOFF" ]; then
  PHASE=$(grep -i '^\#*\s*phase:\?\s*' "$HANDOFF" 2>/dev/null | head -1 | sed 's/^#*\s*[Pp]hase:\?\s*//' | xargs)
  NEXT_TARGET=$(grep -i '^\#*\s*next\s*target\|^\#*\s*current\s*target' "$HANDOFF" 2>/dev/null | head -1 | sed 's/^#*\s*[Nn]ext\s*[Tt]arget:\?\s*//;s/^#*\s*[Cc]urrent\s*[Tt]arget:\?\s*//' | xargs)
fi

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

# Get current branch
BRANCH=$(cd "$CWD" && git branch --show-current 2>/dev/null || echo "unknown")

# Extract guard command from setup.md
GUARD=""
if [ -f "$SETUP" ]; then
  GUARD=$(grep -i 'guard\|test.*command' "$SETUP" 2>/dev/null | head -1 | sed 's/^.*:\s*//' | xargs)
fi

# Write state JSON
jq -n \
  --arg phase "$PHASE" \
  --arg branch "$BRANCH" \
  --arg next_target "$NEXT_TARGET" \
  --arg guard "$GUARD" \
  --argjson total "$TOTAL" \
  --argjson keeps "$KEEPS" \
  --argjson discards "$DISCARDS" \
  '{
    phase: $phase,
    branch: $branch,
    experiments: { total: $total, keeps: $keeps, discards: $discards },
    next_target: $next_target,
    guard: $guard
  }' > "$STATE_FILE"

exit 0
