#!/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 {
}
VAPI

phpast="$work/function_wrapper_missing.phpast"
phpir="$work/function_wrapper_missing.phpir"
valair="$work/function_wrapper_missing.valair"
err="$work/function_wrapper_missing.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 substr because no phpfunc_substr runtime wrapper is known" >&2
    exit 1
fi

actual=$(cat "$err")
for expected_part in \
    'Could not resolve PHP call "substr" to runtime wrapper "phpfunc_substr"' \
    'wrapper is missing from known phpef runtime VAPIs' \
    'selected PHP runtime reports function_exists("substr") = true' \
    'PHP function exists, so this is a PHPEF implementation gap'; 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 - missing wrapper diagnostic distinguishes PHP function_exists=true implementation gap\n'
