#!/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"
valair2vala="$cli_dir/phpefc-valair2vala"
valair_optimize="$cli_dir/phpefc-valair-optimize-typing"

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

phpast="$work/array_literal.phpast"
phpir="$work/array_literal.phpir"
valair="$work/array_literal.valair"
vala="$work/array_literal.vala"

"$php2ast" "$src" "$phpast"
"$phpast2phpir" "$phpast" "$phpir"
"$phpir2valair" "$phpir" "$valair"
"$valair_optimize" "$valair" "$valair.afteropt.typing-zval2static"
"$valair2vala" "$valair.afteropt.typing-zval2static" "$vala"

for needle in 'ArrayLiteral' 'ArrayItem' 'ArrayAppendAssignment'; do
    if ! grep -Fq "$needle" "$phpir"; then
        echo "missing PHP-IR node: $needle" >&2
        cat "$phpir" >&2
        exit 1
    fi
done
for needle in 'StaticCallExpression' 'ConstructExpression' 'ArrayCreationExpression' 'NullLiteral' 'Zval.from_array' 'ZvalArrayEntry'; do
    if ! grep -Fq "$needle" "$valair"; then
        echo "missing Vala-IR node/detail: $needle" >&2
        cat "$valair" >&2
        exit 1
    fi
done
if grep -Fq 'ArrayLiteral' "$valair"; then
    echo "Vala-IR still contains PHP array literal instead of lowered runtime call" >&2
    cat "$valair" >&2
    exit 1
fi
for needle in 'Zval.from_array(new ZvalArrayEntry[] {' 'new ZvalArrayEntry(null, Zval.from_string("a"))' 'a.array_append(Zval.from_string("c"));'; do
    if ! grep -Fq "$needle" "$vala"; then
        echo "missing generated Vala: $needle" >&2
        cat "$vala" >&2
        exit 1
    fi
done

printf '%s\n' 'ok 1 - array literal and append lower through PHP-IR, Vala-IR and generated Vala'
