#!/usr/bin/env bash
# PreCompact hook: Inject state preservation guidance before 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 project status.md — find the most recently modified one
LATEST_STATUS=$(find "$CLAUDE_PROJECT_DIR/.codeflash" -name "status.md" -type f -exec stat -f '%m %N' {} + 2>/dev/null | sort -rn | head -1 | cut -d' ' -f2-)
if [ -n "$LATEST_STATUS" ] && [ -f "$LATEST_STATUS" ]; then
    REL_PATH=${LATEST_STATUS#"$CLAUDE_PROJECT_DIR/"}
    STATUS_CONTENT=$(head -50 "$LATEST_STATUS" 2>/dev/null)
    [ -n "$STATUS_CONTENT" ] && STATE="${STATE}\nActive optimization project (${REL_PATH}):\n${STATUS_CONTENT}\n"
fi

# Handoff document — most recent .claude/handoffs/ file
LATEST_HANDOFF=$(find "$CLAUDE_PROJECT_DIR/.claude" -name "*.handoff.md" -type f 2>/dev/null | head -1)
if [ -n "$LATEST_HANDOFF" ] && [ -f "$LATEST_HANDOFF" ]; then
    HANDOFF_CONTENT=$(head -40 "$LATEST_HANDOFF" 2>/dev/null)
    [ -n "$HANDOFF_CONTENT" ] && STATE="${STATE}\nHandoff context:\n${HANDOFF_CONTENT}\n"
fi

# Key project conventions (from CLAUDE.md section headers + rules)
STATE="${STATE}\nProject conventions to preserve:\n"
STATE="${STATE}- Monorepo: packages/ (UV workspace), plugin/ (self-contained, multi-language: plugin/languages/python/, plugin/languages/javascript/)\n"
STATE="${STATE}- Build: make build-plugin, prek run --all-files (lint), uv run pytest packages/ -v (test)\n"
STATE="${STATE}- Optimization projects in .codeflash/{teammember}/{org}/{project}/ with status.md, bench/, data/results.tsv\n"
STATE="${STATE}- Target repos in ~/Desktop/work/{org}_org/{project}\n"
STATE="${STATE}- VM benchmarks via ssh -A, record to data/results.tsv, update status.md\n"
STATE="${STATE}- Atomic commits, one purpose per commit, verify before committing\n"

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

# Output as JSON with systemMessage for the compaction model
cat <<EOF
{
  "systemMessage": "PRESERVE the following session state through compaction:\n$(echo -e "$STATE" | sed 's/"/\\"/g' | sed ':a;N;$!ba;s/\n/\\n/g')"
}
EOF

exit 0
