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

build_root=$1
src=$2

cli_dir="$build_root/src/cli"
php2ast="$cli_dir/phpefc-php2ast"
phpast2phpir="$cli_dir/phpefc-phpast2phpir"
phpir2valair="$cli_dir/phpefc-phpir2valair"

for tool in "$php2ast" "$phpast2phpir" "$phpir2valair"; 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"

phpast="$work/function_wrong_arity.phpast"
phpir="$work/function_wrong_arity.phpir"
valair="$work/function_wrong_arity.valair"
err="$work/function_wrong_arity.err"

"$php2ast" "$src" "$phpast"
"$phpast2phpir" "$phpast" "$phpir"

set +e
"$phpir2valair" "$phpir" "$valair" >"$err" 2>&1
rc=$?
set -e

if [ "$rc" -eq 0 ]; then
    echo "expected phpir2valair to reject wrong substr argument count" >&2
    exit 1
fi

expected='Could not resolve PHP call "substr" to runtime wrapper "phpfunc_substr"; wrapper expects 2..3 argument(s), got 1'
actual=$(cat "$err")
if [ "$actual" != "$expected" ]; then
    printf 'unexpected diagnostic\nexpected: %s\nactual:   %s\n' "$expected" "$actual" >&2
    exit 1
fi

printf 'ok 1 - PHP function arity diagnostic includes wrapper expected/got counts\n'
