#!/bin/bash
#
# GSD PreCompact Hook
# Saves state before context compaction to enable seamless resume
#
# This hook is triggered by Claude Code before auto/manual compaction.
# Input: JSON on stdin with trigger type and custom_instructions
# Output: Exit 0 to allow compaction, Exit 2 to block
#

set -euo pipefail

# Configuration
PLANNING_DIR="${GSD_PLANNING_DIR:-.planning}"
TIMESTAMP=$(date -Iseconds)
LOG_FILE="${PLANNING_DIR}/events.log"

# Ensure planning directory exists
mkdir -p "$PLANNING_DIR"

# Read hook input (JSON from Claude Code)
INPUT=$(cat)

# Extract trigger type (auto or manual)
TRIGGER=$(echo "$INPUT" | jq -r '.trigger // "unknown"' 2>/dev/null || echo "unknown")

# Log the compaction event
log_event() {
    echo "${TIMESTAMP} | COMPACTION | trigger=${TRIGGER}" >> "$LOG_FILE"
}

# Save continuation context
save_continue_context() {
    local state_content=""

    if [[ -f "${PLANNING_DIR}/STATE.md" ]]; then
        state_content=$(head -50 "${PLANNING_DIR}/STATE.md" 2>/dev/null || echo "")
    fi

    cat > "${PLANNING_DIR}/CONTINUE.md" << EOF
# Continuation Context

**Compacted at:** ${TIMESTAMP}
**Trigger:** ${TRIGGER}

## Resume Instructions

1. Read STATE.md for current phase/task
2. Read current PLAN.md for task details
3. Continue from last checkpoint

## Last Known State

${state_content}

---
*This file is auto-generated by GSD PreCompact hook*
EOF
}

# Save metrics snapshot (if metrics exist)
save_metrics_snapshot() {
    if [[ -f "${PLANNING_DIR}/metrics.json" ]]; then
        cp "${PLANNING_DIR}/metrics.json" "${PLANNING_DIR}/metrics.${TIMESTAMP}.json" 2>/dev/null || true
    fi
}

# Main
main() {
    log_event
    save_continue_context
    save_metrics_snapshot

    # Exit 0 to allow compaction to proceed
    exit 0
}

main
