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

build_root=$1
src=$2
expected_result=$3
expected_breakdown=$4

cli_dir="$build_root/src/cli"
php2ast="$cli_dir/phpefc-php2ast"
phpast2phpir="$cli_dir/phpefc-phpast2phpir"
phpir2valair="$cli_dir/phpefc-phpir2valair"
valair_optimize="$cli_dir/phpefc-valair-optimize-typing"
valair2vala="$cli_dir/phpefc-valair2vala"

for tool in "$php2ast" "$phpast2phpir" "$phpir2valair" "$valair_optimize" "$valair2vala"; do
    if [ ! -x "$tool" ]; then
        echo "missing built tool: $tool" >&2
        exit 99
    fi
done

work=${MESON_TEST_TMPDIR:-}
if [ -z "$work" ]; then
    work=$(mktemp -d)
    trap 'rm -rf "$work"' EXIT
fi
mkdir -p "$work"

base="$work/typing-zval-param-types"
phpast="$base.phpast"
phpir="$base.phpir"
valair="$base.valair"
afteropt="$base.afteropt.typing-zval2static"
vala="$base.vala"

"$php2ast" "$src" "$phpast" >/dev/null
"$phpast2phpir" "$phpast" "$phpir" >/dev/null
"$phpir2valair" "$phpir" "$valair" >/dev/null
"$valair_optimize" "$valair" "$afteropt" >/dev/null
"$valair2vala" "$afteropt" "$vala" >/dev/null

for file in "$phpir" "$valair"; do
    if ! grep -a -Fq 'paramTypes = array(1)' "$file" || ! grep -a -Fq '"n" => "int"' "$file"; then
        echo "expected declared int parameter metadata in $file" >&2
        cat "$file" >&2
        exit 1
    fi
done

result_marker="// phpefc optimizer typing-zval2static result: $expected_result"
breakdown_marker="// phpefc optimizer typing-zval2static breakdown: $expected_breakdown"
for file in "$afteropt" "$vala"; do
    if ! grep -a -Fq "$result_marker" "$file"; then
        echo "expected typing optimizer result marker in $file: $result_marker" >&2
        cat "$file" >&2
        exit 1
    fi
    if ! grep -a -Fq "$breakdown_marker" "$file"; then
        echo "expected typing optimizer breakdown marker in $file: $breakdown_marker" >&2
        cat "$file" >&2
        exit 1
    fi
done

if ! grep -Fq 'int64 n = PhpefRuntimeCore.argument(args, 0).as_int();' "$vala"; then
    echo "expected declared int parameter to lower to an int64 local" >&2
    cat "$vala" >&2
    exit 1
fi
if grep -Fq 'Zval n = PhpefRuntimeCore.argument(args, 0);' "$vala"; then
    echo "declared int parameter stayed as Zval" >&2
    cat "$vala" >&2
    exit 1
fi
if ! grep -Fq 'return Zval.from_float(' "$vala"; then
    echo "expected float return bridge for typed local int expression" >&2
    cat "$vala" >&2
    exit 1
fi

printf 'ok - declared paramTypes flow through PHPIR/ValaIR and drive typing-zval2static (%s; %s)\n' "$expected_result" "$expected_breakdown"
