#!/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/function_missing.phpast"
phpir="$work/function_missing.phpir"
err="$work/function_missing.err"

"$php2ast" "$src" "$phpast"

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

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

expected='Unsupported PHP function call for phpast-ir-v0: ssssstr at line 2; expected runtime wrapper/lowering: phpfunc_ssssstr; the selected PHP runtime reports function_exists("ssssstr") = false; this function is not currently reachable in this PHP runtime/extension set'
actual=$(cat "$err")
if [ "$actual" != "$expected" ]; then
    printf 'unexpected diagnostic\nexpected: %s\nactual:   %s\n' "$expected" "$actual" >&2
    exit 1
fi

printf 'ok 1 - unknown PHP function diagnostic includes name and function_exists=false reachability\n'
