#!/bin/bash

# Exit on error
set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
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"
}

# Validation functions
check_command() {
    if ! command -v $1 &> /dev/null; then
        log_error "$1 is not installed. Please install it first."
        exit 1
    fi
}

check_environment() {
    # Check for required tools
    check_command "node"
    check_command "npm"
    check_command "java"
    
    # Check for Gradle Wrapper instead of system gradle
    if [ ! -f "android/gradlew" ]; then
        log_error "Gradle wrapper not found at android/gradlew"
        exit 1
    fi

    # Check Node.js version
    NODE_VERSION=$(node -v | cut -d. -f1 | tr -d 'v')
    if [ "$NODE_VERSION" -lt 14 ]; then
        log_error "Node.js version 14 or higher is required"
        exit 1
    fi

    # Check Java version
    JAVA_VERSION=$(java -version 2>&1 | head -n 1 | cut -d'"' -f2 | cut -d. -f1)
    if [ "$JAVA_VERSION" -lt 11 ]; then
        log_error "Java version 11 or higher is required"
        exit 1
    fi

    # Check for Android SDK
    if [ -z "$ANDROID_HOME" ]; then
        log_error "ANDROID_HOME environment variable is not set"
        exit 1
    fi
}

# Build functions
build_typescript() {
    log_info "Building TypeScript..."
    npm run clean
    if ! npm run build; then
        log_error "TypeScript build failed"
        exit 1
    fi
}

build_plugin_for_test_app() {
    log_info "Building plugin for test app..."
    
    # Build the plugin AAR
    log_info "Building plugin AAR..."
    cd android || exit 1
    if ! ./gradlew :plugin:clean :plugin:assembleDebug; then
        log_error "Plugin build failed"
        exit 1
    fi
    
    AAR_FILE="plugin/build/outputs/aar/plugin-debug.aar"
    if [ ! -f "$AAR_FILE" ]; then
        log_error "AAR file not found at $AAR_FILE"
        exit 1
    fi
    log_info "Plugin AAR built: $AAR_FILE"
    
    # Remove any stale AAR from test app's libs directory
    if [ -f "../test-apps/daily-notification-test/android/app/libs/plugin-debug.aar" ]; then
        log_info "Removing stale AAR from test app libs..."
        rm "../test-apps/daily-notification-test/android/app/libs/plugin-debug.aar"
    fi
    
    cd ..
    
    # Ensure symlink is in place
    SYMLINK="test-apps/daily-notification-test/node_modules/@timesafari/daily-notification-plugin"
    if [ ! -L "$SYMLINK" ] || [ ! -e "$SYMLINK" ]; then
        log_info "Creating symlink to plugin..."
        mkdir -p "$(dirname "$SYMLINK")"
        rm -f "$SYMLINK"
        ln -sf "../../../" "$SYMLINK"
    fi
    
    # Build test app
    log_info "Building test app..."
    cd test-apps/daily-notification-test/android || exit 1
    
    if ! ./gradlew clean assembleDebug; then
        log_error "Test app build failed"
        exit 1
    fi
    
    APK_FILE="app/build/outputs/apk/debug/app-debug.apk"
    if [ ! -f "$APK_FILE" ]; then
        log_error "APK file not found at $APK_FILE"
        exit 1
    fi
    
    log_info "Test app build successful: $APK_FILE"
    log_info "Install with: adb install -r $APK_FILE"
    
    cd ../../..
}

build_android() {
    log_info "Building Android..."
    
    # Detect project type
    if [ -d "test-apps/daily-notification-test" ]; then
        log_info "Detected test app. Building plugin and test app together..."
        build_plugin_for_test_app
        return 0
    fi
    
    cd android || exit 1

    # Check if this is a plugin development project
    if [ ! -f "capacitor-cordova-android-plugins/cordova.variables.gradle" ]; then
        log_warn "This appears to be a plugin development project"
        log_warn "Android test app not properly initialized"
        
        # =============================================================================
        # AUTOMATIC FIX: capacitor.build.gradle for Plugin Development Projects
        # =============================================================================
        # 
        # PROBLEM: The capacitor.build.gradle file is auto-generated by Capacitor CLI
        # and includes a line that tries to load a file that doesn't exist in plugin
        # development projects:
        #   apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
        #
        # WHY THIS HAPPENS: 
        # - This file is generated by 'npx cap sync', 'npx cap update', etc.
        # - It assumes a full Capacitor app with proper plugin integration
        # - Plugin development projects don't have the full Capacitor setup
        #
        # THE FIX:
        # - Comment out the problematic line to prevent build failures
        # - Add explanatory comment about why it's commented out
        # - This fix gets applied automatically every time the build script runs
        #
        # WHEN THIS FIX GETS OVERWRITTEN:
        # - Running 'npx cap sync' will regenerate the file and remove our fix
        # - Running 'npx cap update' will regenerate the file and remove our fix
        # - Running 'npx cap add android' will regenerate the file and remove our fix
        #
        # HOW TO RESTORE THE FIX:
        # - Run this build script again (it will reapply the fix automatically)
        # - Or run: ./scripts/fix-capacitor-build.sh
        # - Or manually comment out the problematic line
        #
        # =============================================================================
        
        if [ -f "app/capacitor.build.gradle" ]; then
            if grep -q "^apply from: \"../capacitor-cordova-android-plugins/cordova.variables.gradle\"" "app/capacitor.build.gradle"; then
                log_info "🔧 Applying automatic fix to capacitor.build.gradle..."
                log_info "   Reason: Plugin development project missing Capacitor integration files"
                log_info "   Fix: Commenting out problematic 'apply from' line"
                
                # Apply the fix by commenting out the problematic line
                # Handle macOS vs Linux sed differences
                if [[ "$OSTYPE" == "darwin"* ]]; then
                    # macOS sed requires empty string after -i
                    sed -i '' 's/^apply from: "\.\.\/capacitor-cordova-android-plugins\/cordova\.variables\.gradle"/\/\/ Plugin development project - no Capacitor integration files needed\n\/\/ &/' "app/capacitor.build.gradle"
                else
                    # Linux sed
                    sed -i 's/^apply from: "\.\.\/capacitor-cordova-android-plugins\/cordova\.variables\.gradle"/\/\/ Plugin development project - no Capacitor integration files needed\n\/\/ &/' "app/capacitor.build.gradle"
                fi
                
                log_info "✅ Fix applied successfully"
                log_warn "⚠️  Note: This fix will be lost if you run 'npx cap sync' or 'npx cap update'"
                log_info "💡 To restore the fix later, run this build script again or use: ./scripts/fix-capacitor-build.sh"
            else
                log_info "ℹ️  capacitor.build.gradle already has the fix applied"
            fi
        else
            log_warn "⚠️  capacitor.build.gradle not found - this may indicate a different project structure"
        fi
        
        log_warn "Plugin source code has been built successfully"
        log_warn "To test the plugin, use it in a Capacitor app instead"
        cd ..
        return 0
    fi

    # Check for gradle wrapper
    if [ ! -f "./gradlew" ]; then
        log_error "Gradle wrapper not found"
        exit 1
    fi

    # Clean and build
    if ! ./gradlew clean; then
        log_error "Android clean failed"
        exit 1
    fi

    if ! ./gradlew assembleRelease; then
        log_error "Android build failed"
        exit 1
    fi

    # Verify AAR file exists
    AAR_FILE="capacitor-cordova-android-plugins/build/outputs/aar/capacitor-cordova-android-plugins-release.aar"
    if [ ! -f "$AAR_FILE" ]; then
        log_error "AAR file not found at $AAR_FILE"
        exit 1
    fi

    log_info "Android build successful: $AAR_FILE"
    cd ..
}

# Main build process
main() {
    log_info "Starting build process..."
    
    # Parse command line arguments
    BUILD_PLATFORM="all"
    while [[ $# -gt 0 ]]; do
        case $1 in
            --platform)
                BUILD_PLATFORM="$2"
                shift 2
                ;;
            *)
                log_error "Unknown option: $1"
                exit 1
                ;;
        esac
    done

    # Check environment
    check_environment

    # Build TypeScript
    build_typescript

    # Build based on platform
    case $BUILD_PLATFORM in
        "android")
            build_android
            ;;
        "all")
            build_android
            ;;
        *)
            log_error "Invalid platform: $BUILD_PLATFORM. Use 'android' or 'all'"
            exit 1
            ;;
    esac

    log_info "Build completed successfully!"
}

# Run main function with all arguments
main "$@" 