#!/bin/bash

# Exit on error
set -e

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

# Logging functions
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

# Parse command line arguments
REINSTALL_NODE_MODULES=false
CLEAN_GRADLE_CACHE=false
CLEAN_DERIVED_DATA=false

while [[ $# -gt 0 ]]; do
    case $1 in
        --reinstall-node)
            REINSTALL_NODE_MODULES=true
            shift
            ;;
        --clean-gradle-cache)
            CLEAN_GRADLE_CACHE=true
            shift
            ;;
        --clean-derived-data)
            CLEAN_DERIVED_DATA=true
            shift
            ;;
        --all)
            REINSTALL_NODE_MODULES=true
            CLEAN_GRADLE_CACHE=true
            CLEAN_DERIVED_DATA=true
            shift
            ;;
        *)
            log_error "Unknown option: $1"
            echo "Usage: $0 [--reinstall-node] [--clean-gradle-cache] [--clean-derived-data] [--all]"
            exit 1
            ;;
    esac
done

log_info "Starting clean build process..."
log_warn "This will remove all build artifacts and caches"

# Step 1: Clean TypeScript build output
log_step "1. Cleaning TypeScript build output..."
npm run clean 2>/dev/null || log_warn "npm run clean failed (may not exist)"
rm -rf dist/
log_info "✓ TypeScript build output cleaned"

# Step 2: Clean iOS plugin build artifacts
log_step "2. Cleaning iOS plugin build artifacts..."
if [ -d "ios" ]; then
    cd ios
    
    # Remove Pods and Podfile.lock
    if [ -d "Pods" ]; then
        rm -rf Pods/
        log_info "  ✓ Removed Pods/"
    fi
    if [ -f "Podfile.lock" ]; then
        rm -f Podfile.lock
        log_info "  ✓ Removed Podfile.lock"
    fi
    
    # Remove Xcode build artifacts
    if [ -d "DailyNotificationPlugin.xcworkspace/xcuserdata" ]; then
        rm -rf DailyNotificationPlugin.xcworkspace/xcuserdata/
        log_info "  ✓ Removed workspace user data"
    fi
    if [ -d "DailyNotificationPlugin.xcodeproj/xcuserdata" ]; then
        rm -rf DailyNotificationPlugin.xcodeproj/xcuserdata/
        log_info "  ✓ Removed project user data"
    fi
    
    # Remove build directories
    find . -type d -name "build" -exec rm -rf {} + 2>/dev/null || true
    find . -type d -name "DerivedData" -exec rm -rf {} + 2>/dev/null || true
    
    cd ..
    log_info "✓ iOS plugin cleaned"
fi

# Step 3: Clean Android plugin build artifacts
log_step "3. Cleaning Android plugin build artifacts..."
if [ -d "android" ]; then
    cd android
    
    # Remove build directories
    if [ -d "build" ]; then
        rm -rf build/
        log_info "  ✓ Removed build/"
    fi
    if [ -d "app/build" ]; then
        rm -rf app/build/
        log_info "  ✓ Removed app/build/"
    fi
    if [ -d ".gradle" ]; then
        if [ "$CLEAN_GRADLE_CACHE" = true ]; then
            rm -rf .gradle/
            log_info "  ✓ Removed .gradle/ (cache cleaned)"
        else
            log_info "  ℹ .gradle/ preserved (use --clean-gradle-cache to remove)"
        fi
    fi
    
    cd ..
    log_info "✓ Android plugin cleaned"
fi

# Step 4: Clean test app build artifacts
log_step "4. Cleaning test app build artifacts..."
if [ -d "test-apps/daily-notification-test" ]; then
    cd test-apps/daily-notification-test
    
    # Remove symlink
    if [ -L "node_modules/@timesafari/daily-notification-plugin" ]; then
        rm -f node_modules/@timesafari/daily-notification-plugin
        log_info "  ✓ Removed plugin symlink"
    fi
    
    # Remove node_modules (if requested)
    if [ "$REINSTALL_NODE_MODULES" = true ]; then
        if [ -d "node_modules" ]; then
            # Use find to handle permission issues on macOS
            find node_modules -delete 2>/dev/null || rm -rf node_modules/ 2>/dev/null || {
                log_warn "  ⚠ Some files in node_modules/ could not be deleted (permission issues)"
                log_warn "  ℹ You may need to manually remove node_modules/ or use sudo"
            }
            log_info "  ✓ Removed node_modules/ (will reinstall)"
        fi
    fi
    
    # Remove build output
    if [ -d "dist" ]; then
        rm -rf dist/
        log_info "  ✓ Removed dist/"
    fi
    
    # Clean iOS test app
    if [ -d "ios" ]; then
        cd ios/App
        
        # Remove Pods and Podfile.lock
        if [ -d "Pods" ]; then
            rm -rf Pods/
            log_info "  ✓ Removed iOS test app Pods/"
        fi
        if [ -f "Podfile.lock" ]; then
            rm -f Podfile.lock
            log_info "  ✓ Removed iOS test app Podfile.lock"
        fi
        
        # Remove Xcode build artifacts
        if [ -d "App.xcworkspace/xcuserdata" ]; then
            rm -rf App.xcworkspace/xcuserdata/
        fi
        if [ -d "App.xcodeproj/xcuserdata" ]; then
            rm -rf App.xcodeproj/xcuserdata/
        fi
        
        # Remove build directories
        find . -type d -name "build" -exec rm -rf {} + 2>/dev/null || true
        
        cd ../..
    fi
    
    # Clean Android test app
    if [ -d "android" ]; then
        cd android
        
        # Remove build directories
        if [ -d "build" ]; then
            rm -rf build/
            log_info "  ✓ Removed Android test app build/"
        fi
        if [ -d "app/build" ]; then
            rm -rf app/build/
            log_info "  ✓ Removed Android test app app/build/"
        fi
        if [ -d "capacitor-cordova-android-plugins/build" ]; then
            rm -rf capacitor-cordova-android-plugins/build/
            log_info "  ✓ Removed Android test app plugin build/"
        fi
        if [ -d ".gradle" ] && [ "$CLEAN_GRADLE_CACHE" = true ]; then
            rm -rf .gradle/
            log_info "  ✓ Removed Android test app .gradle/ (cache cleaned)"
        fi
        
        cd ..
    fi
    
    cd ../..
    log_info "✓ Test app cleaned"
fi

# Step 5: Clean Xcode DerivedData (if requested)
if [ "$CLEAN_DERIVED_DATA" = true ]; then
    log_step "5. Cleaning Xcode DerivedData..."
    DERIVED_DATA_DIR="$HOME/Library/Developer/Xcode/DerivedData"
    if [ -d "$DERIVED_DATA_DIR" ]; then
        # Find and remove project-specific DerivedData
        find "$DERIVED_DATA_DIR" -maxdepth 1 -type d \( -name "*DailyNotification*" -o -name "*daily-notification*" \) -exec rm -rf {} + 2>/dev/null || true
        log_info "✓ Xcode DerivedData cleaned (project-specific)"
        log_warn "  ℹ To clean all DerivedData, manually delete: $DERIVED_DATA_DIR"
    else
        log_warn "  ℹ DerivedData directory not found: $DERIVED_DATA_DIR"
    fi
fi

# Step 6: Reinstall node_modules (if requested)
if [ "$REINSTALL_NODE_MODULES" = true ]; then
    log_step "6. Reinstalling node_modules..."
    
    # Root node_modules
    if [ -d "node_modules" ]; then
        find node_modules -delete 2>/dev/null || rm -rf node_modules/ 2>/dev/null || {
            log_warn "  ⚠ Some files in root node_modules/ could not be deleted (permission issues)"
            log_warn "  ℹ You may need to manually remove node_modules/ or use sudo"
        }
    fi
    log_info "  Installing root dependencies..."
    npm install
    
    # Test app node_modules
    if [ -d "test-apps/daily-notification-test" ]; then
        cd test-apps/daily-notification-test
        log_info "  Installing test app dependencies..."
        npm install
        cd ../..
    fi
    
    log_info "✓ Dependencies reinstalled"
fi

log_info ""
log_info "════════════════════════════════════════════════════════════"
log_info "Clean build complete! 🎉"
log_info "════════════════════════════════════════════════════════════"
log_info ""
log_info "Next steps:"
log_info "  1. Run: ./scripts/build-native.sh --platform all"
log_info "  2. Or run: ./scripts/build-native.sh --platform ios"
log_info "  3. Or run: ./scripts/build-native.sh --platform android"
log_info ""
log_info "Options used:"
[ "$REINSTALL_NODE_MODULES" = true ] && log_info "  ✓ Reinstalled node_modules"
[ "$CLEAN_GRADLE_CACHE" = true ] && log_info "  ✓ Cleaned Gradle cache"
[ "$CLEAN_DERIVED_DATA" = true ] && log_info "  ✓ Cleaned Xcode DerivedData"
log_info ""
