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

core_vapi="$work/phpef-runtime-core.vapi"
embed_vapi="$work/phpef-runtime-embed.vapi"
cat > "$core_vapi" <<'VAPI'
namespace PhpefRuntimeCore {
    public class Zval {}
}
VAPI
cat > "$embed_vapi" <<'VAPI'
namespace PhpefRuntimeEmbed {
    // PHP Core: function_exists (as zendcall_function_exists); wrapper phpfunc_zendcall_function_exists; zendcall_reason: Core symbol/existence/metadata helpers observe Zend tables; expose only through explicit zendcall_* source names.
    public static PhpefRuntimeCore.Zval phpfunc_zendcall_function_exists (PhpefRuntimeCore.Zval function_name);
}
VAPI

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

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

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

if [ "$rc" -eq 0 ]; then
    echo "expected phpir2valair to reject function_exists because no phpfunc_function_exists runtime wrapper is known" >&2
    exit 1
fi

actual=$(cat "$err")
for expected_part in \
    'Could not resolve PHP call "function_exists" to runtime wrapper "phpfunc_function_exists"' \
    'wrapper is missing from known phpef runtime VAPIs' \
    'available as explicit "zendcall_function_exists()" / wrapper "phpfunc_zendcall_function_exists"' \
    'CAUTION: zendcall_* calls directly into the selected libphp.so/Zend runtime via phpef-runtime-embed'; do
    if [[ "$actual" != *"$expected_part"* ]]; then
        printf 'unexpected diagnostic; missing part: %s\nactual: %s\n' "$expected_part" "$actual" >&2
        exit 1
    fi
done

printf 'ok 1 - function_exists diagnostic explains zendcall-only escape hatch and reason\n'
