#!/bin/bash
set -euo pipefail

# Description: Build all workspace targets for current platform
# Arguments:   [profile] - debug or release (default: debug)
# Returns:     0 on success, 1 on failure
# Output:      Build progress and results

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

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

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

# Function: Validate profile
validate_profile() {
    local profile="$1"
    [[ "$profile" == "debug" || "$profile" == "release" ]] || {
        log_error "Invalid profile: $profile (must be debug or release)"
        return 1
    }
}

# Function: Build workspace
build_workspace() {
    local profile="$1"
    local cargo_args=("--workspace")

    if [[ "$profile" == "release" ]]; then
        cargo_args+=("--release")
    fi

    log_info "Building workspace ($profile profile)..."
    cd "$WORKSPACE_ROOT"
    cargo build "${cargo_args[@]}"
}

# Function: Main entry point
main() {
    log_info "TypeDialog Build All"
    log_info "====================="

    validate_profile "$PROFILE" || return 1
    build_workspace "$PROFILE"

    log_info "Build complete: $PROFILE profile"
    return 0
}

main "$@"
