#!/bin/bash
# Clean script for MbetterClient build artifacts

echo "🧹 MbetterClient Clean Script"
echo "============================"

# Clean build directories
echo "🗂️  Removing build directories..."
if [ -d "build" ]; then
    rm -rf build
    echo "   ✅ Removed: build/"
else
    echo "   ℹ️  Build directory not found"
fi

if [ -d "dist" ]; then
    echo "   🧹 Cleaning dist/ directory (preserving .exe files)..."

    # List files before cleaning
    echo "   📋 Files in dist/ before cleaning:"
    ls -la dist/
    echo ""

    # Remove all files except .exe files
    find dist -type f -not -name "*.exe" -delete 2>/dev/null || true

    # Remove empty directories (but keep the dist directory itself)
    find dist -type d -empty -delete 2>/dev/null || true

    # Check what remains
    remaining_files=$(find dist -type f | wc -l)
    remaining_exe=$(find dist -name "*.exe" | wc -l)

    if [ "$remaining_files" -gt 0 ]; then
        echo "   ✅ Cleaned: Removed all artifacts, preserved $remaining_exe .exe file(s)"
        echo "   📋 Files remaining in dist/:"
        ls -la dist/
    else
        echo "   ℹ️  No files remain in dist/ directory"
    fi
else
    echo "   ℹ️  Dist directory not found"
fi

# Clean generated spec files
echo "📄 Removing generated spec files..."
if [ -f "MbetterClient.spec" ]; then
    rm -f MbetterClient.spec
    echo "   ✅ Removed: MbetterClient.spec"
else
    echo "   ℹ️  MbetterClient.spec not found"
fi

if [ -f "mbetter_discovery.spec" ]; then
    rm -f mbetter_discovery.spec
    echo "   ✅ Removed: mbetter_discovery.spec"
else
    echo "   ℹ️  mbetter_discovery.spec not found"
fi

# Clean packages directory (optional)
echo "📦 Clean packages directory? (y/N)"
read -r response
if [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]; then
    if [ -d "packages" ]; then
        rm -rf packages
        echo "   ✅ Removed: packages/"
    else
        echo "   ℹ️  Packages directory not found"
    fi
fi

# Clean __pycache__ directories
echo "🐍 Removing Python cache files..."
find . -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null || true
find . -name "*.pyc" -delete 2>/dev/null || true
find . -name "*.pyo" -delete 2>/dev/null || true

echo ""
echo "✅ Clean completed!"
echo ""
echo "To rebuild, run: ./build.sh"