#!/bin/bash
set -euo pipefail

# Description: Cross-compile for multiple platforms using cargo-cross
# Arguments:   [target] - specific target (default: all targets)
# Returns:     0 on success, 1 on failure
# Output:      Cross-compilation progress

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly SCRIPT_DIR
WORKSPACE_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
readonly WORKSPACE_ROOT
readonly TARGET="${1:-}"

# Supported targets for cross-compilation
declare -a TARGETS=(
    "x86_64-unknown-linux-gnu"
    "x86_64-apple-darwin"
    "aarch64-apple-darwin"
    "x86_64-pc-windows-gnu"
)

# Function: Print info message
log_info() {
    echo "[INFO] $*" >&2
}

# Function: Print error message
log_error() {
    echo "[ERROR] $*" >&2
}

# Function: Check for cross tool
check_cross() {
    command -v cross >/dev/null || {
        log_error "cross not found. Install: cargo install cross"
        return 1
    }
}

# Function: Validate target
is_valid_target() {
    local target="$1"
    for t in "${TARGETS[@]}"; do
        [[ "$t" == "$target" ]] && return 0
    done
    return 1
}

# Function: Build single target
build_target() {
    local target="$1"
    log_info "Building target: $target"

    cd "$WORKSPACE_ROOT"
    cross build --target "$target" --release
}

# Function: Build all targets
build_all_targets() {
    local failed=0

    for target in "${TARGETS[@]}"; do
        if ! build_target "$target"; then
            log_error "Failed to build: $target"
            ((failed++))
        fi
    done

    return $((failed > 0 ? 1 : 0))
}

# Function: Main entry point
main() {
    log_info "TypeDialog Cross-Compilation"
    log_info "=============================="

    check_cross || return 1

    if [[ -z "$TARGET" ]]; then
        log_info "Building all targets..."
        build_all_targets
    else
        is_valid_target "$TARGET" || {
            log_error "Invalid target: $TARGET"
            log_error "Supported: ${TARGETS[*]}"
            return 1
        }
        build_target "$TARGET"
    fi

    log_info "Cross-compilation complete"
    return 0
}

main "$@"
