#!/bin/bash
# auto-run.sh
# Author: Matthew Raymer
# Description: Smart auto-run script that detects devices and automatically launches
# the appropriate target for test and production builds
#
# This script can:
# - Detect connected Android devices vs emulators
# - Detect connected iOS devices vs simulators  
# - Automatically launch Electron app
# - Choose the best available target for each platform
#
# Usage:
#   ./scripts/auto-run.sh [--test|--prod] [--platform=ios|android|electron|all]
#
# Exit Codes:
# 0 - Success
# 1 - No devices found
# 2 - Build failed
# 3 - Launch failed

# Exit on any error
set -e

# Source common utilities
source "$(dirname "$0")/common.sh"

# Default values
BUILD_MODE="development"
PLATFORM="all"
AUTO_CONFIRM=false

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --test)
            BUILD_MODE="test"
            shift
            ;;
        --prod)
            BUILD_MODE="production"
            shift
            ;;
        --platform=*)
            PLATFORM="${1#*=}"
            shift
            ;;
        --auto)
            AUTO_CONFIRM=true
            shift
            ;;
        --help)
            echo "Usage: $0 [--test|--prod] [--platform=ios|android|electron|all] [--auto]"
            echo ""
            echo "Options:"
            echo "  --test          Build and run in test mode"
            echo "  --prod          Build and run in production mode"
            echo "  --platform=PLATFORM  Target platform (ios|android|electron|all)"
            echo "  --auto          Skip confirmation prompts"
            echo "  --help          Show this help message"
            exit 0
            ;;
        *)
            log_error "Unknown option: $1"
            exit 1
            ;;
    esac
done

# Print header
print_header "TimeSafari Auto-Run"
log_info "Build mode: $BUILD_MODE"
log_info "Target platform: $PLATFORM"
log_info "Auto confirm: $AUTO_CONFIRM"

# Function to detect Android devices
detect_android_devices() {
    log_step "Detecting Android devices..."
    
    # Check if adb is available
    if ! command -v adb &> /dev/null; then
        log_warn "ADB not found - Android detection skipped"
        return 1
    fi
    
    # Get list of devices
    local devices_output=$(adb devices 2>/dev/null || echo "")
    local devices=()
    local emulators=()
    
    # Parse device list
    while IFS= read -r line; do
        if [[ $line =~ ^([a-zA-Z0-9.-]+)[[:space:]]+device$ ]]; then
            local device_id="${BASH_REMATCH[1]}"
            
            # Check if it's an emulator (emulator IDs typically contain 'emulator')
            if [[ $device_id == *"emulator"* ]]; then
                emulators+=("$device_id")
            else
                devices+=("$device_id")
            fi
        fi
    done <<< "$devices_output"
    
    # Log results
    if [ ${#devices[@]} -gt 0 ]; then
        log_success "Found ${#devices[@]} real Android device(s): ${devices[*]}"
    fi
    
    if [ ${#emulators[@]} -gt 0 ]; then
        log_success "Found ${#emulators[@]} Android emulator(s): ${emulators[*]}"
    fi
    
    if [ ${#devices[@]} -eq 0 ] && [ ${#emulators[@]} -eq 0 ]; then
        log_warn "No Android devices or emulators found"
        return 1
    fi
    
    # Return device type and ID
    if [ ${#devices[@]} -gt 0 ]; then
        echo "real:${devices[0]}"
    else
        echo "emulator:${emulators[0]}"
    fi
}

# Function to detect iOS devices
detect_ios_devices() {
    log_step "Detecting iOS devices..."
    
    # Check if xcrun is available
    if ! command -v xcrun &> /dev/null; then
        log_warn "xcrun not found - iOS detection skipped"
        return 1
    fi
    
    # Get list of devices
    local devices_output=$(xcrun xctrace list devices 2>/dev/null || echo "")
    local devices=()
    local simulators=()
    
    # Parse device list
    while IFS= read -r line; do
        # Look for real devices (containing "iPhone" or "iPad" but not "Simulator")
        if [[ $line =~ iPhone|iPad ]] && [[ $line != *"Simulator"* ]]; then
            if [[ $line =~ \(([A-F0-9-]+)\) ]]; then
                local device_id="${BASH_REMATCH[1]}"
                devices+=("$device_id")
            fi
        fi
        
        # Look for simulators
        if [[ $line =~ Simulator ]]; then
            if [[ $line =~ \(([A-F0-9-]+)\) ]]; then
                local simulator_id="${BASH_REMATCH[1]}"
                simulators+=("$simulator_id")
            fi
        fi
    done <<< "$devices_output"
    
    # Log results
    if [ ${#devices[@]} -gt 0 ]; then
        log_success "Found ${#devices[@]} real iOS device(s): ${devices[*]}"
    fi
    
    if [ ${#simulators[@]} -gt 0 ]; then
        log_success "Found ${#simulators[@]} iOS simulator(s): ${simulators[*]}"
    fi
    
    if [ ${#devices[@]} -eq 0 ] && [ ${#simulators[@]} -eq 0 ]; then
        log_warn "No iOS devices or simulators found"
        return 1
    fi
    
    # Return device type and ID
    if [ ${#devices[@]} -gt 0 ]; then
        echo "real:${devices[0]}"
    else
        echo "simulator:${simulators[0]}"
    fi
}

# Function to build and run Android
run_android() {
    local device_info=$1
    local device_type=$(echo "$device_info" | cut -d: -f1)
    local device_id=$(echo "$device_info" | cut -d: -f2)
    
    log_step "Building and running Android ($device_type: $device_id)..."
    
    # Build the app
    if [ "$BUILD_MODE" = "test" ]; then
        safe_execute "Building Android (test)" "npm run build:android:test"
    elif [ "$BUILD_MODE" = "production" ]; then
        safe_execute "Building Android (production)" "npm run build:android:prod"
    else
        safe_execute "Building Android (development)" "npm run build:android:dev"
    fi
    
    # Run the app
    if [ "$device_type" = "real" ]; then
        log_info "Installing and launching on real device: $device_id"
        safe_execute "Installing APK" "adb -s $device_id install -r android/app/build/outputs/apk/debug/app-debug.apk"
        safe_execute "Launching app" "adb -s $device_id shell am start -n app.timesafari.app/app.timesafari.MainActivity"
    else
        log_info "Launching emulator and installing app"
        safe_execute "Launching app" "npx cap run android"
    fi
}

# Function to build and run iOS
run_ios() {
    local device_info=$1
    local device_type=$(echo "$device_info" | cut -d: -f1)
    local device_id=$(echo "$device_info" | cut -d: -f2)
    
    log_step "Building and running iOS ($device_type: $device_id)..."
    
    # Build the app
    if [ "$BUILD_MODE" = "test" ]; then
        safe_execute "Building iOS (test)" "npm run build:ios:test"
    elif [ "$BUILD_MODE" = "production" ]; then
        safe_execute "Building iOS (production)" "npm run build:ios:prod"
    else
        safe_execute "Building iOS (development)" "npm run build:ios:dev"
    fi
    
    # Run the app
    if [ "$device_type" = "real" ]; then
        log_info "Building and installing on real device: $device_id"
        safe_execute "Building for device" "npm run build:ios:release"
        # Note: For real devices, you'd typically need to use Xcode
        log_warn "Real device deployment requires Xcode setup"
    else
        log_info "Launching simulator and installing app"
        safe_execute "Launching app" "npx cap run ios"
    fi
}

# Function to build and run Electron
run_electron() {
    log_step "Building and running Electron..."
    
    # Build the app
    if [ "$BUILD_MODE" = "test" ]; then
        safe_execute "Building Electron (test)" "npm run build:electron:test"
    elif [ "$BUILD_MODE" = "production" ]; then
        safe_execute "Building Electron (production)" "npm run build:electron:prod"
    else
        safe_execute "Building Electron (development)" "npm run build:electron:dev"
    fi
    
    # Run the app
    log_info "Launching Electron app"
    safe_execute "Launching Electron" "npm run electron:start"
}

# Main execution
main() {
    log_info "Starting auto-run at $(date)"
    
    # Detect available platforms
    local android_device=""
    local ios_device=""
    local electron_available=true
    
    # Check Android
    if [ "$PLATFORM" = "all" ] || [ "$PLATFORM" = "android" ]; then
        android_device=$(detect_android_devices) || log_warn "Android not available"
    fi
    
    # Check iOS (only on macOS)
    if [ "$PLATFORM" = "all" ] || [ "$PLATFORM" = "ios" ]; then
        if [ "$(uname)" = "Darwin" ]; then
            ios_device=$(detect_ios_devices) || log_warn "iOS not available"
        else
            log_warn "iOS not available on non-macOS platform"
        fi
    fi
    
    # Check Electron
    if [ "$PLATFORM" = "all" ] || [ "$PLATFORM" = "electron" ]; then
        if ! command -v electron &> /dev/null; then
            log_warn "Electron not available"
            electron_available=false
        fi
    fi
    
    # Show available options
    log_info "Available targets:"
    [ -n "$android_device" ] && log_info "  Android: $android_device"
    [ -n "$ios_device" ] && log_info "  iOS: $ios_device"
    [ "$electron_available" = true ] && log_info "  Electron: available"
    
    # Confirm with user (unless auto mode)
    if [ "$AUTO_CONFIRM" = false ]; then
        echo ""
        read -p "Continue with auto-run? (y/N): " -n 1 -r
        echo ""
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            log_info "Auto-run cancelled by user"
            exit 0
        fi
    fi
    
    # Execute based on platform selection
    local success_count=0
    
    if [ "$PLATFORM" = "android" ] || [ "$PLATFORM" = "all" ]; then
        if [ -n "$android_device" ]; then
            if run_android "$android_device"; then
                ((success_count++))
            fi
        fi
    fi
    
    if [ "$PLATFORM" = "ios" ] || [ "$PLATFORM" = "all" ]; then
        if [ -n "$ios_device" ]; then
            if run_ios "$ios_device"; then
                ((success_count++))
            fi
        fi
    fi
    
    if [ "$PLATFORM" = "electron" ] || [ "$PLATFORM" = "all" ]; then
        if [ "$electron_available" = true ]; then
            if run_electron; then
                ((success_count++))
            fi
        fi
    fi
    
    # Summary
    if [ $success_count -gt 0 ]; then
        log_success "Auto-run completed successfully! $success_count platform(s) launched."
    else
        log_error "No platforms were successfully launched"
        exit 1
    fi
}

# Run main function
main "$@" 