#!/bin/bash
# Archipelago Deep Cleanup Script
# Removes ALL development caches and build artifacts safely
# This is more aggressive than cleanup-mac.sh but 100% safe

set -e

echo "╔════════════════════════════════════════════════════════════════╗"
echo "║  Archipelago DEEP Cleanup                                      ║"
echo "╚════════════════════════════════════════════════════════════════╝"
echo ""
echo "This will remove ALL caches and temporary files."
echo "Everything can be rebuilt when needed."
echo ""

TOTAL_SAVED=0

# Function to calculate and display savings
calc_savings() {
    local path="$1"
    if [ -e "$path" ]; then
        local size=$(du -sk "$path" | cut -f1)
        TOTAL_SAVED=$((TOTAL_SAVED + size))
    fi
}

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "PROJECT DIRECTORY CLEANUP"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

# 1. Remove Rust build artifacts
if [ -d "core/target" ]; then
    echo "🧹 Removing Rust build cache..."
    calc_savings "core/target"
    rm -rf core/target
    echo "   ✅ Removed core/target/"
fi

# 2. Remove node_modules (can be reinstalled with npm install)
if [ -d "neode-ui/node_modules" ]; then
    echo "🧹 Removing node_modules (180 MB)..."
    calc_savings "neode-ui/node_modules"
    rm -rf neode-ui/node_modules
    echo "   ✅ Removed neode-ui/node_modules/"
    echo "   ℹ️  Run 'npm install' in neode-ui/ to restore"
fi

# 3. Remove local dist builds (built to remote server anyway)
if [ -d "neode-ui/dist" ]; then
    echo "🧹 Removing local frontend builds..."
    calc_savings "neode-ui/dist"
    rm -rf neode-ui/dist
    echo "   ✅ Removed neode-ui/dist/"
fi

if [ -d "web/dist" ]; then
    calc_savings "web/dist"
    rm -rf web/dist
    echo "   ✅ Removed web/dist/"
fi

# 4. Remove .DS_Store files
echo "🧹 Removing .DS_Store files..."
find . -name ".DS_Store" -type f -delete 2>/dev/null || true
echo "   ✅ Removed all .DS_Store files"

# 5. Remove ISO build artifacts
if [ -d "image-recipe/build" ]; then
    echo "🧹 Removing ISO build artifacts..."
    calc_savings "image-recipe/build"
    rm -rf image-recipe/build
    echo "   ✅ Removed image-recipe/build/"
fi

# 6. Keep only the latest ISO
if [ -d "image-recipe/results" ]; then
    ISO_COUNT=$(ls -1 image-recipe/results/*.iso 2>/dev/null | wc -l | tr -d ' ')
    if [ "$ISO_COUNT" -gt 1 ]; then
        echo "🧹 Cleaning old ISOs (keeping latest)..."
        cd image-recipe/results
        ls -t *.iso | tail -n +2 | while read iso; do
            calc_savings "$iso"
            rm "$iso"
        done
        cd ../..
        echo "   ✅ Kept latest ISO only"
    fi
fi

# 7. Optimize Git repository
echo "🧹 Optimizing Git repository..."
BEFORE_GIT=$(du -sk .git | cut -f1)
git gc --aggressive --prune=now 2>&1 | grep -v "^Enumerating" | grep -v "^Counting" | head -5 || true
AFTER_GIT=$(du -sk .git | cut -f1)
GIT_SAVED=$((BEFORE_GIT - AFTER_GIT))
TOTAL_SAVED=$((TOTAL_SAVED + GIT_SAVED))
echo "   ✅ Git repository optimized"

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "SYSTEM-WIDE CACHE CLEANUP"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

# 8. Clean Cargo cache (keeps only essential files)
if [ -d ~/.cargo/registry ]; then
    echo "🧹 Cleaning Cargo registry cache..."
    calc_savings ~/.cargo/registry
    cargo cache -a 2>/dev/null || rm -rf ~/.cargo/registry/cache ~/.cargo/registry/src 2>/dev/null || true
    echo "   ✅ Cleaned Cargo cache (~177 MB)"
fi

# 9. Clean npm cache
if [ -d ~/.npm ]; then
    echo "🧹 Cleaning npm cache..."
    calc_savings ~/.npm
    npm cache clean --force 2>/dev/null || true
    echo "   ✅ Cleaned npm cache (~249 MB)"
fi

# 10. Clean Homebrew cache
if [ -d ~/Library/Caches/Homebrew ]; then
    echo "🧹 Cleaning Homebrew cache..."
    calc_savings ~/Library/Caches/Homebrew
    brew cleanup 2>/dev/null || true
    rm -rf ~/Library/Caches/Homebrew/* 2>/dev/null || true
    echo "   ✅ Cleaned Homebrew cache (~890 MB)"
fi

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "DOCKER DESKTOP (Manual Step)"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

DOCKER_SIZE=$(du -sk ~/Library/Containers/com.docker.docker 2>/dev/null | cut -f1 || echo "0")
if [ "$DOCKER_SIZE" -gt 1000000 ]; then
    DOCKER_GB=$((DOCKER_SIZE / 1024 / 1024))
    echo "⚠️  Docker Desktop: ~${DOCKER_GB} GB"
    echo "   To remove: Open Docker Desktop → Settings → Troubleshoot → Uninstall"
    echo "   OR run: ./remove-docker.sh"
fi

echo ""
echo "╔════════════════════════════════════════════════════════════════╗"
echo "║  DEEP Cleanup Complete!                                        ║"
echo "╚════════════════════════════════════════════════════════════════╝"
echo ""

SAVED_GB=$((TOTAL_SAVED / 1024 / 1024))
echo "💾 Total space saved: ~${SAVED_GB} GB"
echo ""
echo "✅ What's left (all you need):"
echo "   - Source code only (no caches)"
echo "   - Latest ISO file"
echo "   - Documentation"
echo ""
echo "ℹ️  To restore development dependencies:"
echo "   cd neode-ui && npm install"
echo ""
echo "🚀 Your workflow (unchanged):"
echo "   ./scripts/deploy-to-target.sh --live"
echo "   (builds remotely, no local dependencies needed)"
echo ""
