#!/bin/bash
# Clean up old parallel-dev runs while preserving important ones

# Configuration
RETENTION_DAYS=${1:-30}
RUNS_DIR=".bmad-workspace/ck-parallel-dev/runs"
ARCHIVE_DIR=".bmad-workspace/ck-parallel-dev/archive"

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

echo "🧹 Parallel-Dev Run Cleanup"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Retention period: $RETENTION_DAYS days"
echo ""

# Create directories if needed
mkdir -p "$ARCHIVE_DIR"

# Check if runs directory exists
if [ ! -d "$RUNS_DIR" ]; then
    echo -e "${RED}Error: Runs directory not found: $RUNS_DIR${NC}"
    exit 1
fi

# Count runs before cleanup
TOTAL_BEFORE=$(find "$RUNS_DIR" -maxdepth 1 -type d -name "2*" | wc -l)
SPACE_BEFORE=$(du -sh "$RUNS_DIR" 2>/dev/null | cut -f1)

echo "Current status:"
echo "  Total runs: $TOTAL_BEFORE"
echo "  Space used: $SPACE_BEFORE"
echo ""

# Find and process old runs
REMOVED_COUNT=0
ARCHIVED_COUNT=0

find "$RUNS_DIR" -maxdepth 1 -type d -name "2*" -mtime +$RETENTION_DAYS | while read -r dir; do
    run_id=$(basename "$dir")
    
    # Check if this run should be archived
    should_archive=false
    archive_reason=""
    
    # Check for failed runs
    if [ -f "$dir/execution-plan.json" ]; then
        recommendation=$(jq -r '.validation_results.recommendation' "$dir/execution-plan.json" 2>/dev/null)
        if [ "$recommendation" = "ABORT" ]; then
            should_archive=true
            archive_reason="Failed run (ABORT)"
        fi
    fi
    
    # Check for rollback executed
    if [ -f "$dir/rollback-executed" ]; then
        should_archive=true
        archive_reason="Rollback executed"
    fi
    
    # Check for high-risk runs
    if [ -f "$dir/execution-plan.json" ]; then
        risk_level=$(jq -r '.execution_strategy.risk_level' "$dir/execution-plan.json" 2>/dev/null)
        if [ "$risk_level" = "high" ]; then
            should_archive=true
            archive_reason="High-risk run"
        fi
    fi
    
    # Archive if needed
    if [ "$should_archive" = true ]; then
        echo -e "${YELLOW}📦 Archiving $run_id ($archive_reason)${NC}"
        tar -czf "$ARCHIVE_DIR/$run_id.tar.gz" -C "$dir" . 2>/dev/null
        
        # Create metadata file
        cat > "$ARCHIVE_DIR/$run_id.meta" <<EOF
{
  "archived_at": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")",
  "original_path": "$dir",
  "reason": "$archive_reason",
  "size": "$(du -sh "$ARCHIVE_DIR/$run_id.tar.gz" | cut -f1)"
}
EOF
        ((ARCHIVED_COUNT++))
    fi
    
    # Remove the run directory
    echo -e "${RED}🗑️  Removing $run_id${NC}"
    rm -rf "$dir"
    ((REMOVED_COUNT++))
done

# Update latest symlink
if [ -x "./utils/manage-latest-symlink.sh" ]; then
    ./utils/manage-latest-symlink.sh update >/dev/null 2>&1
fi

# Count runs after cleanup
TOTAL_AFTER=$(find "$RUNS_DIR" -maxdepth 1 -type d -name "2*" | wc -l)
SPACE_AFTER=$(du -sh "$RUNS_DIR" 2>/dev/null | cut -f1)

# Summary
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo -e "${GREEN}✅ Cleanup Complete${NC}"
echo ""
echo "Summary:"
echo "  Runs removed: $REMOVED_COUNT"
echo "  Runs archived: $ARCHIVED_COUNT"
echo "  Runs remaining: $TOTAL_AFTER"
echo "  Space before: $SPACE_BEFORE"
echo "  Space after: $SPACE_AFTER"
echo ""

# Check archive size
if [ -d "$ARCHIVE_DIR" ]; then
    ARCHIVE_SIZE=$(du -sh "$ARCHIVE_DIR" 2>/dev/null | cut -f1)
    ARCHIVE_COUNT=$(ls "$ARCHIVE_DIR"/*.tar.gz 2>/dev/null | wc -l)
    echo "Archive status:"
    echo "  Total archives: $ARCHIVE_COUNT"
    echo "  Archive size: $ARCHIVE_SIZE"
fi

echo ""
echo "💡 Tip: To change retention period, run:"
echo "   $0 <days>"
echo ""