#!/bin/bash

# StackMemory Claude Hook: Auto-detect compaction and rehydrate context
# This hook runs when Claude Code compaction is detected

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}🔍 StackMemory: Compaction detected, attempting context rehydration...${NC}"

# Check if StackMemory is available
if ! command -v stackmemory &> /dev/null; then
    echo -e "${YELLOW}⚠️  StackMemory CLI not found. Install with: npm install -g @stackmemoryai/stackmemory${NC}"
    exit 0
fi

# Check if we're in a StackMemory project
if ! stackmemory status &> /dev/null; then
    echo -e "${YELLOW}⚠️  Not a StackMemory project. Initialize with: stackmemory init${NC}"
    exit 0
fi

# Check for existing checkpoints
echo -e "${BLUE}📋 Checking for rehydration checkpoints...${NC}"
if stackmemory context rehydrate --list 2>/dev/null | grep -q "No rehydration checkpoints"; then
    echo -e "${YELLOW}📝 No checkpoints found. Creating initial checkpoint...${NC}"
    if stackmemory context rehydrate --create; then
        echo -e "${GREEN}✅ Initial checkpoint created${NC}"
    else
        echo -e "${RED}❌ Failed to create checkpoint${NC}"
        exit 1
    fi
else
    echo -e "${GREEN}📁 Found existing checkpoints${NC}"
fi

# Perform context rehydration
echo -e "${BLUE}🔄 Rehydrating context...${NC}"
if stackmemory context rehydrate --verbose; then
    echo -e "${GREEN}✅ Context successfully rehydrated${NC}"
    echo -e "${GREEN}💡 Your session now has rich context including:${NC}"
    echo -e "${GREEN}   • File snapshots and content previews${NC}"
    echo -e "${GREEN}   • Project structure and relationships${NC}"
    echo -e "${GREEN}   • Previous decisions and reasoning${NC}"
    echo -e "${GREEN}   • Active workflows and focus areas${NC}"
else
    echo -e "${RED}❌ Context rehydration failed${NC}"
    echo -e "${YELLOW}💡 You can manually create a checkpoint with: stackmemory context rehydrate --create${NC}"
fi

echo -e "${BLUE}🎯 StackMemory compaction recovery complete${NC}"