#!/bin/bash
# PostCompact hook: re-inject optimization state summary into Claude's context.
# Reads .codeflash/.compact-state.json and echoes a concise summary to stdout.
# Output goes directly into Claude's context as a system reminder.

set -euo pipefail

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

STATE_FILE="$CWD/.codeflash/.compact-state.json"

# Nothing to inject if no saved state
if [ ! -f "$STATE_FILE" ]; then
  exit 0
fi

# Read state
PHASE=$(jq -r '.phase // "unknown"' "$STATE_FILE")
BRANCH=$(jq -r '.branch // "unknown"' "$STATE_FILE")
TOTAL=$(jq -r '.experiments.total // 0' "$STATE_FILE")
KEEPS=$(jq -r '.experiments.keeps // 0' "$STATE_FILE")
DISCARDS=$(jq -r '.experiments.discards // 0' "$STATE_FILE")
NEXT_TARGET=$(jq -r '.next_target // ""' "$STATE_FILE")
GUARD=$(jq -r '.guard // ""' "$STATE_FILE")

# Build summary line
SUMMARY="[codeflash state] Phase: $PHASE | Experiments: $TOTAL (${KEEPS} keeps, ${DISCARDS} discards) | Branch: $BRANCH"

if [ -n "$NEXT_TARGET" ] && [ "$NEXT_TARGET" != "null" ]; then
  SUMMARY="$SUMMARY | Next target: $NEXT_TARGET"
fi

if [ -n "$GUARD" ] && [ "$GUARD" != "null" ]; then
  SUMMARY="$SUMMARY | Guard: $GUARD"
fi

# Echo to stdout — this becomes a system reminder in Claude's context
echo "$SUMMARY"
echo "Read .codeflash/HANDOFF.md and .codeflash/results.tsv for full session state."

exit 0
