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

build_root=$1
entry_src=$2
lib_src=$3

cli_dir="$build_root/src/cli"
php2ast="$cli_dir/phpefc-php2ast"
phpast2phpir="$cli_dir/phpefc-phpast2phpir"
phpir2valair="$cli_dir/phpefc-phpir2valair"
valair2vala="$cli_dir/phpefc-valair2vala"
valair_optimize="$cli_dir/phpefc-valair-optimize-typing"

source_prefix() {
    python3 - "$1" <<'PY'
import re, sys
path = sys.argv[1].replace('\\', '/')
path = path.rsplit('/', 1)[-1]
part = re.sub(r'[^A-Za-z0-9_]+', '_', path).strip('_') or 'unknown_php'
if not re.match(r'^[A-Za-z_]', part):
    part = '_' + part
print(part)
PY
}

work=${MESON_TEST_TMPDIR:-}
if [ -z "$work" ]; then
    work=$(mktemp -d)
    trap 'rm -rf "$work"' EXIT
fi
mkdir -p "$work"

lib_prefix=$(source_prefix "$(realpath "$lib_src")")
lib_register="phpef_file_${lib_prefix}__register_functions"
lib_call='PhpefRuntimeCore.call_function("included_func",'

entry_ast="$work/noinclude_entry.phpast"
lib_ast="$work/include_lib.phpast"
entry_phpir="$work/noinclude_entry.phpir"
lib_phpir="$work/include_lib.phpir"
entry_valair="$work/noinclude_entry.valair"
lib_valair="$work/include_lib.valair"
entry_vala="$work/noinclude_entry.vala"
lib_vala="$work/include_lib.vala"

"$php2ast" "$entry_src" "$entry_ast" >/dev/null
"$php2ast" "$lib_src" "$lib_ast" >/dev/null
"$phpast2phpir" "$entry_ast" "$entry_phpir" --external-phpast "$lib_ast" >/dev/null
"$phpast2phpir" "$lib_ast" "$lib_phpir" --external-phpast "$entry_ast" >/dev/null
"$phpir2valair" "$entry_phpir" "$entry_valair" --external-phpir "$lib_phpir" >/dev/null
"$phpir2valair" "$lib_phpir" "$lib_valair" --external-phpir "$entry_phpir" >/dev/null
"$valair_optimize" "$entry_valair" "$entry_valair.afteropt.typing-zval2static" >/dev/null
"$valair_optimize" "$lib_valair" "$lib_valair.afteropt.typing-zval2static" >/dev/null
"$valair2vala" "$entry_valair.afteropt.typing-zval2static" "$entry_vala" >/dev/null
"$valair2vala" "$lib_valair.afteropt.typing-zval2static" "$lib_vala" --no-main >/dev/null

if ! grep -Fq "${lib_call}" "$entry_vala"; then
    echo 'expected external function call to lower through runtime registry' >&2
    cat "$entry_vala" >&2
    exit 1
fi
if grep -Fq "${lib_register}();" "$entry_vala"; then
    echo 'external function without include must not register support-file functions' >&2
    cat "$entry_vala" >&2
    exit 1
fi

if grep -Fq '__registered' "$entry_vala" || grep -Fq '__call(' "$entry_vala"; then
    echo 'old bool/__call registration model leaked into generated Vala' >&2
    cat "$entry_vala" >&2
    exit 1
fi

printf 'ok 1 - source-set external function without include lowers to unregistered runtime registry call\n'
