#!/bin/bash

# Clear Cache Script for BCT Development
# This script clears all types of caches that might interfere with development

echo "🧹 Starting comprehensive cache clearing..."

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

# Function to print colored output
print_step() {
    echo -e "${BLUE}$1${NC}"
}

print_success() {
    echo -e "${GREEN}✅ $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠️ $1${NC}"
}

print_error() {
    echo -e "${RED}❌ $1${NC}"
}

# 1. Clear Node.js module cache
print_step "1. Clearing Node.js module cache..."
rm -rf node_modules/.cache 2>/dev/null || true
print_success "Node.js cache cleared"

# 2. Clear npm cache
print_step "2. Clearing npm cache..."
npm cache clean --force 2>/dev/null || true
print_success "npm cache cleared"

# 3. Clear Astro build cache
print_step "3. Clearing Astro build cache..."
rm -rf .astro 2>/dev/null || true
rm -rf dist 2>/dev/null || true
print_success "Astro cache cleared"

# 4. Clear Docker build cache
print_step "4. Clearing Docker build cache..."
docker builder prune -a -f 2>/dev/null || print_warning "Docker not available or permission denied"
print_success "Docker build cache cleared"

# 5. Clear Docker containers and images
print_step "5. Stopping and removing Docker containers..."
docker-compose down 2>/dev/null || true
docker system prune -a -f 2>/dev/null || print_warning "Docker system prune failed"
print_success "Docker containers and images cleared"

# 6. Clear any temporary files
print_step "6. Clearing temporary files..."
rm -rf tmp/ 2>/dev/null || true
rm -rf .tmp/ 2>/dev/null || true
rm -rf logs/*.log 2>/dev/null || true
print_success "Temporary files cleared"

# 7. Clear Vite cache
print_step "7. Clearing Vite cache..."
rm -rf node_modules/.vite 2>/dev/null || true
print_success "Vite cache cleared"

# 8. Clear TypeScript cache
print_step "8. Clearing TypeScript cache..."
rm -rf node_modules/.cache/typescript 2>/dev/null || true
print_success "TypeScript cache cleared"

echo ""
print_success "🎉 All caches cleared successfully!"
echo ""
echo -e "${YELLOW}Next steps:${NC}"
echo "1. Hard refresh your browser (Ctrl+Shift+R or Cmd+Shift+R)"
echo "2. Open browser dev tools and disable cache (Network tab)"
echo "3. Run: npm run docker:build --no-cache"
echo "4. Run: npm run docker:up"
echo ""
echo -e "${BLUE}For persistent cache issues, also try:${NC}"
echo "• Clear browser data/cookies for localhost:3000"
echo "• Use incognito/private browsing mode"
echo "• Add ?v=\$(date +%s) to URLs for cache busting"