#!/bin/bash
#
# Cleanup Script - Remove Prunable Files
# This script removes duplicate files, cache artifacts, and other files identified for pruning.
#
# Usage: ./scripts/cleanup-prune-files.sh [options]
# Options:
#   --dry-run    Show what would be deleted without actually deleting
#   --backup     Create backups before deleting
#   --all        Run all cleanup operations
#   --duplicates Remove duplicate files only
#   --cache      Remove cache files only
#   --help       Show this help message
#

set -uo pipefail

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

# Flags
DRY_RUN=false
BACKUP=false
RUN_ALL=false
RUN_DUPLICATES=false
RUN_CACHE=false

# Counters
FILES_DELETED=0
FILES_BACKED_UP=0
FILES_SKIPPED=0

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --dry-run)
            DRY_RUN=true
            shift
            ;;
        --backup)
            BACKUP=true
            shift
            ;;
        --all)
            RUN_ALL=true
            shift
            ;;
        --duplicates)
            RUN_DUPLICATES=true
            shift
            ;;
        --cache)
            RUN_CACHE=true
            shift
            ;;
        --help)
            echo "Usage: $0 [options]"
            echo "Options:"
            echo "  --dry-run    Show what would be deleted without actually deleting"
            echo "  --backup     Create backups before deleting"
            echo "  --all        Run all cleanup operations"
            echo "  --duplicates Remove duplicate files only"
            echo "  --cache      Remove cache files only"
            echo "  --help       Show this help message"
            exit 0
            ;;
        *)
            echo -e "${RED}Unknown option: $1${NC}"
            echo "Use --help for usage information"
            exit 1
            ;;
    esac
done

# If no specific operation selected, default to all
if [[ "$RUN_ALL" == false && "$RUN_DUPLICATES" == false && "$RUN_CACHE" == false ]]; then
    RUN_ALL=true
fi

# Function to delete file with optional backup
delete_file() {
    local file="$1"
    local reason="$2"
    
    if [[ ! -f "$file" ]]; then
        echo -e "${YELLOW}  ⚠ Skipping (not found): $file${NC}"
        ((FILES_SKIPPED++))
        return
    fi
    
    if [[ "$DRY_RUN" == true ]]; then
        echo -e "${YELLOW}  [DRY RUN] Would delete: $file${NC}"
        echo -e "    Reason: $reason"
        ((FILES_DELETED++))
        return
    fi
    
    if [[ "$BACKUP" == true ]]; then
        local backup_file="${file}.backup.$(date +%Y%m%d_%H%M%S)"
        cp "$file" "$backup_file"
        echo -e "${GREEN}  ✓ Backed up: $backup_file${NC}"
        ((FILES_BACKED_UP++))
    fi
    
    rm -f "$file"
    echo -e "${GREEN}  ✓ Deleted: $file${NC}"
    echo -e "    Reason: $reason"
    ((FILES_DELETED++))
}

# Function to delete files matching pattern
delete_files_pattern() {
    local pattern="$1"
    local reason="$2"
    
    while IFS= read -r -d '' file; do
        delete_file "$file" "$reason"
    done < <(find . -name "$pattern" -type f -print0 2>/dev/null)
}

echo "=========================================="
echo "File Cleanup Script"
echo "=========================================="
echo ""

if [[ "$DRY_RUN" == true ]]; then
    echo -e "${YELLOW}DRY RUN MODE - No files will be deleted${NC}"
    echo ""
fi

if [[ "$BACKUP" == true ]]; then
    echo -e "${YELLOW}BACKUP MODE - Backups will be created${NC}"
    echo ""
fi

# 1. Remove duplicate infrastructure data files from public/
if [[ "$RUN_ALL" == true || "$RUN_DUPLICATES" == true ]]; then
    echo "1. Removing duplicate infrastructure data files..."
    echo "   (Keeping versions in docs/infrastructure/data/)"
    echo ""
    
    duplicates=(
        "public/docs/infrastructure/data/cost_estimates.json"
        "public/docs/infrastructure/data/deployment_timeline.json"
        "public/docs/infrastructure/data/compliance_requirements.json"
    )
    
    for file in "${duplicates[@]}"; do
        delete_file "$file" "Duplicate - original exists in docs/infrastructure/data/"
    done
    echo ""
fi

# 2. Remove webpack cache .old files
if [[ "$RUN_ALL" == true || "$RUN_CACHE" == true ]]; then
    echo "2. Removing webpack cache .old files..."
    echo ""
    
    delete_files_pattern "*.old" "Old webpack cache file (will be regenerated)"
    
    # Also target specific webpack cache locations
    webpack_cache_files=(
        ".next/cache/webpack/client-development/index.pack.gz.old"
        ".next/cache/webpack/server-development/index.pack.gz.old"
        "portal/.next/cache/webpack/client-development/index.pack.gz.old"
        "portal/.next/cache/webpack/server-development/index.pack.gz.old"
    )
    
    for file in "${webpack_cache_files[@]}"; do
        delete_file "$file" "Old webpack cache file (will be regenerated)"
    done
    echo ""
fi

# Summary
echo "=========================================="
echo "Summary"
echo "=========================================="
echo -e "${GREEN}Files deleted: $FILES_DELETED${NC}"
if [[ "$BACKUP" == true ]]; then
    echo -e "${GREEN}Files backed up: $FILES_BACKED_UP${NC}"
fi
if [[ $FILES_SKIPPED -gt 0 ]]; then
    echo -e "${YELLOW}Files skipped: $FILES_SKIPPED${NC}"
fi
echo ""

if [[ "$DRY_RUN" == true ]]; then
    echo -e "${YELLOW}This was a dry run. Run without --dry-run to actually delete files.${NC}"
fi

echo "Done!"

