#!/bin/bash
# RSSuper Multi-Platform Build Script
# Main entry point for building all platforms

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

# Source common utilities
source "$SCRIPT_DIR/common.sh"

# Default values
PLATFORMS="all"
BUILD_TYPE="debug"
ACTION="build"
RUN_TESTS=false

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

# Show help
show_help() {
    cat << EOF
RSSuper Multi-Platform Build System

Usage: $0 [OPTIONS]

Options:
  -p, --platforms PLATFORMS  Comma-separated platforms (ios,android,linux) or 'all' [Default: all]
  -t, --type TYPE            Build type (debug|release) [Default: debug]
  -a, --action ACTION        Action to perform (build|test|clean|install) [Default: build]
  --test                     Run tests after build
  -h, --help                Show this help message

Platforms:
  ios      iOS/macOS (requires macOS)
  android  Android
  linux    Linux (GTK4)

Examples:
  $0                              # Build all platforms in debug mode
  $0 -p ios,android -t release    # Build iOS and Android in release mode
  $0 -p linux --test              # Build and test Linux version
  $0 -a clean                     # Clean all platforms
  $0 -p ios -a install           # Install iOS app to simulator

EOF
}

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        -p|--platforms)
            PLATFORMS="$2"
            shift 2
            ;;
        -t|--type)
            BUILD_TYPE="$2"
            shift 2
            ;;
        -a|--action)
            ACTION="$2"
            shift 2
            ;;
        --test)
            RUN_TESTS=true
            shift
            ;;
        -h|--help)
            show_help
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            show_help
            exit 1
            ;;
    esac
done

# Track build results
declare -A BUILD_RESULTS
TOTAL_PLATFORMS=0
SUCCESSFUL_BUILDS=0

# Build iOS/macOS
build_ios() {
    log_info "Building iOS/macOS..."
    
    if [[ "$OSTYPE" != "darwin"* ]]; then
        log_warning "iOS/macOS build requires macOS. Skipping."
        BUILD_RESULTS["ios"]="skipped"
        return 0
    fi
    
    cd "$PROJECT_ROOT"
    
    case "$ACTION" in
        clean)
            "$SCRIPT_DIR/build-ios.sh" clean
            ;;
        test)
            "$SCRIPT_DIR/build-ios.sh" "$BUILD_TYPE" ios "generic/platform=iOS" test
            ;;
        build|*)
            if "$SCRIPT_DIR/build-ios.sh" "$BUILD_TYPE" ios "generic/platform=iOS" build; then
                BUILD_RESULTS["ios"]="success"
                ((SUCCESSFUL_BUILDS++)) || true
            else
                BUILD_RESULTS["ios"]="failed"
            fi
            
            if [ "$RUN_TESTS" = true ]; then
                log_info "Running iOS tests..."
                "$SCRIPT_DIR/build-ios.sh" "$BUILD_TYPE" ios "generic/platform=iOS" test || true
            fi
            ;;
    esac
}

# Build Android
build_android() {
    log_info "Building Android..."
    
    cd "$PROJECT_ROOT"
    
    case "$ACTION" in
        clean)
            "$SCRIPT_DIR/build-android.sh" "$BUILD_TYPE" clean
            ;;
        test)
            "$SCRIPT_DIR/build-android.sh" "$BUILD_TYPE" test
            ;;
        build|*)
            if "$SCRIPT_DIR/build-android.sh" "$BUILD_TYPE" assemble; then
                BUILD_RESULTS["android"]="success"
                ((SUCCESSFUL_BUILDS++)) || true
            else
                BUILD_RESULTS["android"]="failed"
            fi
            
            if [ "$RUN_TESTS" = true ]; then
                log_info "Running Android tests..."
                "$SCRIPT_DIR/build-android.sh" "$BUILD_TYPE" test || true
            fi
            ;;
    esac
}

# Build Linux
build_linux() {
    log_info "Building Linux..."
    
    cd "$PROJECT_ROOT"
    
    case "$ACTION" in
        clean)
            "$SCRIPT_DIR/build-linux.sh" "$BUILD_TYPE" clean
            ;;
        test)
            "$SCRIPT_DIR/build-linux.sh" "$BUILD_TYPE" test
            ;;
        build|*)
            if "$SCRIPT_DIR/build-linux.sh" "$BUILD_TYPE" build; then
                BUILD_RESULTS["linux"]="success"
                ((SUCCESSFUL_BUILDS++)) || true
            else
                BUILD_RESULTS["linux"]="failed"
            fi
            
            if [ "$RUN_TESTS" = true ]; then
                log_info "Running Linux tests..."
                "$SCRIPT_DIR/build-linux.sh" "$BUILD_TYPE" test || true
            fi
            ;;
    esac
}

# Print build summary
print_summary() {
    echo ""
    log_info "=== Build Summary ==="
    echo ""
    
    printf "%-12s | %-10s | %s\n" "Platform" "Status" "Details"
    printf "%-12s-+-%-10s-+-%s\n" "------------" "----------" "-------"
    
    for platform in "${!BUILD_RESULTS[@]}"; do
        local status="${BUILD_RESULTS[$platform]}"
        local status_symbol=""
        
        case "$status" in
            success)
                status_symbol="✅"
                ;;
            failed)
                status_symbol="❌"
                ;;
            skipped)
                status_symbol="⏭️"
                ;;
        esac
        
        printf "%-12s | %-10s | %s\n" "$platform" "$status" "$status_symbol"
    done
    
    echo ""
    echo "Total: $SUCCESSFUL_BUILDS / ${#BUILD_RESULTS[@]} platforms built successfully"
    echo ""
}

# Main
echo "========================================"
echo "  RSSuper Multi-Platform Build System"
echo "========================================"
echo ""
echo "Configuration:"
echo "  Platforms: $PLATFORMS"
echo "  Build Type: $BUILD_TYPE"
echo "  Action: $ACTION"
echo "  Run Tests: $RUN_TESTS"
echo ""

# Convert platforms string to array
IFS=',' read -ra PLATFORM_ARRAY <<< "$PLATFORMS"

# Build each platform
for platform in "${PLATFORM_ARRAY[@]}"; do
    platform=$(echo "$platform" | xargs) # Trim whitespace
    ((TOTAL_PLATFORMS++)) || true
    
    case "$platform" in
        all)
            build_ios
            build_android
            build_linux
            ((TOTAL_PLATFORMS+=2)) || true # Add extra platforms
            ;;
        ios)
            build_ios
            ;;
        android)
            build_android
            ;;
        linux)
            build_linux
            ;;
        *)
            log_error "Unknown platform: $platform"
            exit 1
            ;;
    esac
done

# Print summary
print_summary

# Exit with error if any builds failed
if [ "$SUCCESSFUL_BUILDS" -lt "${#BUILD_RESULTS[@]}" ]; then
    # Filter out skipped builds
    local actual_builds=0
    for result in "${BUILD_RESULTS[@]}"; do
        if [ "$result" != "skipped" ]; then
            ((actual_builds++)) || true
        fi
    done
    
    if [ "$SUCCESSFUL_BUILDS" -lt "$actual_builds" ]; then
        log_error "Some builds failed"
        exit 1
    fi
fi

log_success "All builds completed successfully!"
