#!/usr/bin/env bash
# Plugin PreCompact hook: Preserve optimization session state through context compaction.
# Gathers current session state so the compaction model retains critical info.

cd "$CLAUDE_PROJECT_DIR" 2>/dev/null || exit 0

STATE=""

# Current branch
BRANCH=$(git branch --show-current 2>/dev/null)
[ -n "$BRANCH" ] && STATE="${STATE}Branch: ${BRANCH}\n"

# Uncommitted files (count + list)
DIRTY=$(git status --porcelain 2>/dev/null)
if [ -n "$DIRTY" ]; then
    COUNT=$(echo "$DIRTY" | wc -l | tr -d ' ')
    STATE="${STATE}Uncommitted files (${COUNT}):\n${DIRTY}\n"
fi

# Unpushed commits
UPSTREAM=$(git rev-parse --abbrev-ref '@{upstream}' 2>/dev/null)
if [ -n "$UPSTREAM" ]; then
    AHEAD=$(git rev-list --count "${UPSTREAM}..HEAD" 2>/dev/null)
    [ "$AHEAD" -gt 0 ] 2>/dev/null && STATE="${STATE}Unpushed commits: ${AHEAD}\n"
fi

# Recent commits on this branch (last 5)
RECENT=$(git log --oneline -5 2>/dev/null)
[ -n "$RECENT" ] && STATE="${STATE}Recent commits:\n${RECENT}\n"

# Optimization session state
if [ -f ".codeflash/HANDOFF.md" ]; then
    HANDOFF=$(head -30 ".codeflash/HANDOFF.md" 2>/dev/null)
    [ -n "$HANDOFF" ] && STATE="${STATE}\nOptimization session (HANDOFF.md):\n${HANDOFF}\n"
fi

if [ -f ".codeflash/results.tsv" ]; then
    LINES=$(wc -l < ".codeflash/results.tsv" | tr -d ' ')
    TAIL=$(tail -5 ".codeflash/results.tsv" 2>/dev/null)
    STATE="${STATE}\nExperiment history (${LINES} entries, last 5):\n${TAIL}\n"
fi

if [ -f ".codeflash/conventions.md" ]; then
    CONV=$(head -20 ".codeflash/conventions.md" 2>/dev/null)
    [ -n "$CONV" ] && STATE="${STATE}\nConventions:\n${CONV}\n"
fi

if [ -f ".codeflash/setup.md" ]; then
    SETUP=$(head -15 ".codeflash/setup.md" 2>/dev/null)
    [ -n "$SETUP" ] && STATE="${STATE}\nSetup:\n${SETUP}\n"
fi

[ -z "$STATE" ] && exit 0

# Output as JSON with systemMessage for the compaction model
ESCAPED=$(echo -e "$STATE" | awk '{ gsub(/"/, "\\\""); gsub(/\t/, "\\t"); if (NR>1) printf "\\n"; printf "%s", $0 }')
cat <<EOF
{
  "systemMessage": "PRESERVE the following session state through compaction:\\n${ESCAPED}"
}
EOF

exit 0
