#!/usr/bin/env bash
# run.sh — build and execute the text/ acceptance corpus.
#
# Each examples/<case>.el is a self-contained El program with a fn main()
# that prints a single deterministic result line. The runner compiles each
# via the canonical native elc, links it against the shared C runtime, runs
# it, and asserts the output matches the expected value.

set -uo pipefail
cd "$(dirname "$0")"

EL_HOME="${EL_HOME:-$(cd ../.. && pwd)}"
ELC="${ELC:-${EL_HOME}/dist/platform/elc}"
RUNTIME_DIR="${EL_HOME}/el-compiler/runtime"

if [ ! -x "${ELC}" ]; then
    echo "elc not found at ${ELC}" >&2
    exit 1
fi

PASS=0
FAIL=0
FAILED_NAMES=()

run_runtime_case() {
    local name="$1"
    local src="$2"
    local expected="$3"

    local out_c
    local out_bin
    out_c="$(mktemp -t text_test.XXXXXX).c"
    out_bin="$(mktemp -t text_test.XXXXXX)"

    if ! "${ELC}" "${src}" > "${out_c}" 2>/tmp/text_test.elc.err; then
        echo "FAIL  ${name} — elc emit failed:"
        cat /tmp/text_test.elc.err | sed 's/^/      /'
        FAIL=$((FAIL+1))
        FAILED_NAMES+=("${name}")
        rm -f "${out_c}" "${out_bin}"
        return
    fi

    if ! cc -O2 -I "${RUNTIME_DIR}" "${out_c}" "${RUNTIME_DIR}/el_runtime.c" \
            -lcurl -lssl -lcrypto -lpthread -lm -o "${out_bin}" 2>/tmp/text_test.cc.err; then
        echo "FAIL  ${name} — cc failed:"
        cat /tmp/text_test.cc.err | sed 's/^/      /'
        FAIL=$((FAIL+1))
        FAILED_NAMES+=("${name}")
        rm -f "${out_c}" "${out_bin}"
        return
    fi

    local got
    got="$("${out_bin}" 2>&1)"

    if [ "${got}" = "${expected}" ]; then
        echo "PASS  ${name}"
        PASS=$((PASS+1))
    else
        echo "FAIL  ${name}  expected: '${expected}', got: '${got}'"
        FAIL=$((FAIL+1))
        FAILED_NAMES+=("${name}")
    fi

    rm -f "${out_c}" "${out_bin}"
}

echo "==> Running text-primitives acceptance corpus"
echo

run_runtime_case "count-substring"          examples/count-substring.el          "3"
run_runtime_case "count-overlap-skip"       examples/count-overlap-skip.el       "2"
run_runtime_case "count-lines-words-letters" examples/count-lines-words-letters.el "2/4/22"
run_runtime_case "index-of-all"             examples/index-of-all.el             "2,5,8"
run_runtime_case "transform-suite"          examples/transform-suite.el          "ababab|olleh|bar|hello|hello"
run_runtime_case "char-classes"             examples/char-classes.el             "true"
run_runtime_case "split-lines"              examples/split-lines.el              "3"
run_runtime_case "join"                     examples/join.el                     "alpha, beta, gamma"

echo
echo "${PASS} passed, ${FAIL} failed"
if [ "${FAIL}" -gt 0 ]; then
    echo "failed: ${FAILED_NAMES[*]}"
    exit 1
fi
exit 0
