default: build

build profile="release":
    #!/usr/bin/env bash
    set -euo pipefail

    # First build normally to show any errors to the user
    cargo build --profile {{profile}}

    # If successful, build again with JSON format to get artifact info (quietly)
    wasm_file=$(
      cargo build --message-format=json --profile {{profile}} --quiet \
        | jq -r 'select(.reason=="compiler-artifact") | .filenames[] | select(endswith(".wasm"))' \
        | tail -n1
    )

    if [[ -z "${wasm_file:-}" ]]; then
      echo "Error: no .wasm artifact found" >&2
      exit 1
    fi

    if [[ "{{profile}}" == "release" ]]; then
        opt_file="${wasm_file%.wasm}.opt.wasm"
        echo "Optimizing: $wasm_file"
        echo "        ->  $opt_file"
        npx @bytecodealliance/jco opt -o "$opt_file" "$wasm_file"
    fi

test:
    #!/usr/bin/env bash
    set -euo pipefail
    
    # Temporarily rename the cargo config to disable build-std for tests
    if [ -f .cargo/config.toml ]; then
        mv .cargo/config.toml .cargo/config.toml.bak
        trap 'mv .cargo/config.toml.bak .cargo/config.toml' EXIT
    fi
    
    cargo test --features std -- --nocapture

clean:
    cargo clean
