#!/bin/bash
# RSSuper iOS/macOS Build Script
# Adapted from Nessa build scripts

set -e

# Configuration
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
IOS_PROJECT_DIR="$PROJECT_ROOT/native-route/ios/RSSuper"
IOS_PROJECT="$IOS_PROJECT_DIR/RSSuper.xcodeproj"
IOS_SCHEME="RSSuper"

# Default values
CONFIGURATION="${1:-Debug}"
PLATFORM="${2:-iOS}"
DESTINATION="${3:-generic/platform=iOS}"
ACTION="${4:-build}"

# Show help
show_help() {
    echo "RSSuper iOS/macOS Build Script"
    echo ""
    echo "Usage: $0 [CONFIGURATION] [PLATFORM] [DESTINATION] [ACTION]"
    echo ""
    echo "Arguments:"
    echo "  CONFIGURATION    Build configuration (Debug|Release) [Default: Debug]"
    echo "  PLATFORM         Target platform (iOS|macOS) [Default: iOS]"
    echo "  DESTINATION      xcodebuild destination [Default: generic/platform=iOS]"
    echo "  ACTION           Action to perform (build|test|clean) [Default: build]"
    echo ""
    echo "Examples:"
    echo "  $0                              # Build Debug for iOS"
    echo "  $0 Release                      # Build Release for iOS"
    echo "  $0 Debug iOS 'platform=iOS Simulator,name=iPhone 15'  # Build for simulator"
    echo "  $0 clean                       # Clean build"
}

# Check if xcodebuild is available
check_prerequisites() {
    if ! command -v xcodebuild &> /dev/null; then
        echo "Error: xcodebuild not found. Please install Xcode."
        exit 1
    fi
    
    if [ ! -d "$IOS_PROJECT_DIR" ]; then
        echo "Error: iOS project directory not found: $IOS_PROJECT_DIR"
        exit 1
    fi
    
    if [ ! -f "$IOS_PROJECT/project.pbxproj" ]; then
        echo "Error: Xcode project not found: $IOS_PROJECT"
        exit 1
    fi
}

# Select appropriate Xcode version
select_xcode() {
    echo "Checking Xcode installation..."
    
    echo "=== Current xcode-select path ==="
    xcode-select -p 2>/dev/null || echo "xcode-select failed"
    echo "=== Current Xcode version ==="
    xcodebuild -version 2>/dev/null || echo "xcodebuild failed"
    
    # Try common Xcode paths in order of preference
    for path in \
        "/Applications/Xcode_16.3.app/Contents/Developer" \
        "/Applications/Xcode_16.2.app/Contents/Developer" \
        "/Applications/Xcode_16.1.app/Contents/Developer" \
        "/Applications/Xcode_16.0.app/Contents/Developer" \
        "/Applications/Xcode_15.4.app/Contents/Developer" \
        "/Applications/Xcode_15.3.app/Contents/Developer" \
        "/Applications/Xcode_15.2.app/Contents/Developer" \
        "/Applications/Xcode_15.1.app/Contents/Developer" \
        "/Applications/Xcode_15.0.app/Contents/Developer" \
        "/Applications/Xcode.app/Contents/Developer"
    do
        if [ -d "$path" ]; then
            CURRENT_PATH=$(xcode-select -p 2>/dev/null || echo "")
            if [ "$CURRENT_PATH" != "$path" ]; then
                echo "Switching Xcode to: $path"
                xcode-select -s "$path" || true
            else
                echo "Xcode already selected at: $path"
            fi
            break
        fi
    done
    
    echo "=== Selected Xcode ==="
    xcodebuild -version
}

# Clean build artifacts
clean_build() {
    echo "Cleaning build artifacts..."
    cd "$IOS_PROJECT_DIR"
    xcodebuild clean \
        -project "$IOS_PROJECT" \
        -scheme "$IOS_SCHEME" \
        -configuration "$CONFIGURATION" \
        -destination "$DESTINATION"
    echo "Clean completed"
}

# Build the project
build_project() {
    echo "Building $PLATFORM $CONFIGURATION..."
    
    cd "$IOS_PROJECT_DIR"
    
    # Capture build output
    BUILD_LOG=$(mktemp)
    
    set +e
    xcodebuild $ACTION \
        -project "$IOS_PROJECT" \
        -scheme "$IOS_SCHEME" \
        -configuration "$CONFIGURATION" \
        -destination "$DESTINATION" \
        > "$BUILD_LOG" 2>&1
    BUILD_EXIT=$?
    set -e
    
    # Show build output
    cat "$BUILD_LOG"
    
    if [ "$BUILD_EXIT" = "0" ]; then
        echo "Build completed successfully!"
        return 0
    else
        echo "Build failed with exit code: $BUILD_EXIT"
        
        # Extract and show errors
        echo ""
        echo "Errors found:"
        grep -E "\.swift:[0-9]+:[0-9]+: error:" "$BUILD_LOG" | head -10 || true
        return $BUILD_EXIT
    fi
}

# Run tests
run_tests() {
    echo "Running tests for $PLATFORM..."
    
    cd "$IOS_PROJECT_DIR"
    
    xcodebuild test \
        -project "$IOS_PROJECT" \
        -scheme "$IOS_SCHEME" \
        -configuration "$CONFIGURATION" \
        -destination "$DESTINATION" \
        ONLY_ACTIVE_ARCH=NO
}

# Main
case "$ACTION" in
    clean)
        check_prerequisites
        select_xcode
        clean_build
        ;;
    test)
        check_prerequisites
        select_xcode
        run_tests
        ;;
    build|*)
        check_prerequisites
        select_xcode
        build_project
        ;;
esac
