#!/usr/bin/env bash
set -euo pipefail

build_root=${1:?build root missing}
test_dir=${2:?test dir missing}

cli_dir="$build_root/src/cli"
php2ast="$cli_dir/phpefc-php2ast"
phpast2phpir="$cli_dir/phpefc-phpast2phpir"
phpir2valair="$cli_dir/phpefc-phpir2valair"
valair_optimize_typing="$cli_dir/phpefc-valair-optimize-typing"
valair_optimize_fastpath_runtime="$cli_dir/phpefc-valair-optimize-fastpath-runtime"
valair_optimize_library="$cli_dir/phpefc-valair-optimize-library"
valair_optimize_precompute="$cli_dir/phpefc-valair-optimize-precompute"
valair2vala="$cli_dir/phpefc-valair2vala"

for tool in "$php2ast" "$phpast2phpir" "$phpir2valair" "$valair_optimize_typing" "$valair_optimize_fastpath_runtime" "$valair_optimize_library" "$valair_optimize_precompute" "$valair2vala"; do
    if [ ! -x "$tool" ]; then
        echo "missing tool: $tool" >&2
        exit 2
    fi
done

work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
mkdir -p "$work/src" "$work/build"
cp -a "$test_dir"/. "$work/src"/

cd "$work/src"
"$php2ast" main.php "$work/build/main.phpast"
"$phpast2phpir" "$work/build/main.phpast" "$work/build/main.phpir"
"$phpir2valair" "$work/build/main.phpir" "$work/build/main.valair.1"
"$valair_optimize_typing" --suppress-warning "$work/build/main.valair.1" "$work/build/main.valair.2.typing"
"$valair_optimize_fastpath_runtime" "$work/build/main.valair.2.typing" "$work/build/main.valair.3.fastpath-runtime"
"$valair_optimize_library" "$work/build/main.valair.3.fastpath-runtime" "$work/build/main.valair.4.library"
"$valair_optimize_typing" "$work/build/main.valair.4.library" "$work/build/main.valair.5.typing-final"
"$valair_optimize_precompute" "$work/build/main.valair.5.typing-final" "$work/build/main.valair.6.precompute"
"$valair2vala" "$work/build/main.valair.6.precompute" "$work/build/main.vala"

if grep -Fq '__phpefc_array_union' "$work/build/main.vala"; then
    echo 'generated Vala still contains __phpefc_array_union helper' >&2
    sed -n '1,160p' "$work/build/main.vala" >&2
    exit 1
fi

if ! grep -Fq '.add(' "$work/build/main.vala"; then
    echo 'generated Vala no longer uses Zval.add() for array plus assignment fixture' >&2
    sed -n '1,160p' "$work/build/main.vala" >&2
    exit 1
fi

echo 'ok - array plus assignment lowers to Zval.add() without generated array-union helper'
