#!/usr/bin/env bash
# Control for temporal adjudication as a query.
#
# The emitter records which illegal combination it saw and still emits a
# TIME_TYPE_ERROR placeholder -- it has to emit SOMETHING for an illegal
# expression. What moved out is the judgment and the wording.
set -uo pipefail
ELC="${1:?usage: temporal_query.sh <elc>}"
LANG_DIR="${2:-$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)}"
W=$(mktemp -d); trap 'rm -rf "$W"' EXIT; F=0
chk(){ [ "$2" = "$3" ] && printf '  ok    %s\n' "$1" || { printf '  FAIL  %s\n    expected %s got %s\n' "$1" "$2" "$3"; F=$((F+1)); }; }
cd "$LANG_DIR"

printf 'fn main() {\n    let a: Instant = now()\n    let b: Instant = now()\n    let c: Instant = a + b\n    println("x")\n}\n' > "$W/b.el"
EL_RELATIONS_OUT="$W/r.txt" "$ELC" "$W/b.el" >/dev/null 2>&1
chk "the illegal combination is recorded, not judged, by the emitter" \
    "1" "$(grep -c 'temporal:instant_plus_instant' "$W/r.txt")"
chk "the emitter no longer authors the message" \
    "0" "$("$ELC" "$W/b.el" 2>/dev/null | grep -c 'is not allowed')"
chk "a placeholder is still emitted for the illegal expression" \
    "1" "$("$ELC" "$W/b.el" 2>/dev/null | grep -c TIME_TYPE_ERROR)"
out=$("./tools/check/temporal.sh" "$W/r.txt" 2>&1); rc=$?
chk "the query judges it" "1" "$rc"
chk "and explains why, from data" "1" "$(echo "$out" | grep -c 'a point plus a point is not a point')"

printf 'fn main() {\n    let a: Instant = now()\n    let d: Duration = el_duration_from_nanos(1)\n    let c: Instant = a + d\n    println("x")\n}\n' > "$W/g.el"
EL_RELATIONS_OUT="$W/r2.txt" "$ELC" "$W/g.el" >/dev/null 2>&1
"./tools/check/temporal.sh" "$W/r2.txt" >/dev/null 2>&1
chk "a legal program exits 0" "0" "$?"
echo; echo "  6 assertions, $((6-F)) passed, $F failed"; exit $F
