#!/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"

for tool in "$php2ast" "$phpast2phpir"; 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/unsupported_expression_dynamic_call.phpast"
phpir="$work/unsupported_expression_dynamic_call.phpir"
err="$work/unsupported_expression_dynamic_call.err"

"$php2ast" "$src" "$phpast" >/dev/null

set +e
"$phpast2phpir" "$phpast" "$phpir" >"$err" 2>&1
rc=$?
set -e

if [ "$rc" -eq 0 ]; then
    echo "expected phpast2phpir to reject unsupported dynamic function call expression" >&2
    exit 1
fi

expected='Unsupported PHP expression for phpast-ir-v0: PhpParser\Node\Expr\FuncCall at line 4; dynamic function name cannot be resolved statically yet'
actual=$(cat "$err")
if [ "$actual" != "$expected" ]; then
    printf 'unexpected diagnostic\nexpected: %s\nactual:   %s\n' "$expected" "$actual" >&2
    exit 1
fi

printf 'ok 1 - unsupported expression diagnostic includes PHP source line\n'
