#!/usr/bin/env bash
# misc_repl_half_step_continuation — feeding a reply across REPL steps must
# CONTINUE the paused RTC, not collapse the trail.
#
# A provides handler that makes a requires out-call suspends mid-RTC ("end of
# trail; stopping here", awaiting the reply). Under `simulate --repl --output
# json` the next op is the reply, fed as a SEPARATE op WITHOUT the produced
# out-call token (the daemon's op-feed omits engine-produced events). The
# renderer needs the out-call before the reply, so run_repl_json must rebase the
# reply onto the rendered trail. A regression (13fc94d8) collapsed the trail to
# `[p.get]` + a spurious non-compliance; this pins the full continuation.
#
# The standard simulate-repl corpus never caught it: its traces are trail-basis
# (produced out-calls included), so token-basis never collapses. This feeds the
# reply-direct op stream the daemon uses.
set -euo pipefail

work="$NUCTEST_TMPDIR/half_step_repl"
rm -rf "$work"; mkdir -p "$work"; cd "$work"

cat > half_step.dzn <<'DZN'
interface ibool {
    in bool get();
    behavior {
        on get: reply(false);
        on get: reply(true);
    }
}
component get_bool {
    provides ibool p;
    requires ibool r;
    behavior {
        on p.get(): {
            bool res = r.get();
            reply(r.get());
        }
    }
}
DZN

ops=$(printf '%s\n' \
  '{"op":"event","event":"p.get"}' \
  '{"op":"event","event":"r.false"}' \
  '{"op":"event","event":"r.true"}' \
  '{"op":"quit"}')

final_trail=$(printf '%s\n' "$ops" \
  | "$NUCLEOS" --output json simulate --repl -m get_bool half_step.dzn 2>/dev/null \
  | python3 -c '
import sys, json
last = None
for line in sys.stdin:
    line = line.strip()
    if not line: continue
    d = json.loads(line)
    tr = d.get("trace")
    if tr is not None:
        last = tr.get("trail")
print(json.dumps(last))')

expected='["p.get", "r.get", "r.false", "r.get", "r.true", "p.true"]'
if [[ "$final_trail" != "$expected" ]]; then
  echo "FAIL: half-step reply continuation collapsed the trail"
  echo "--- expected ---"; printf '%s\n' "$expected"
  echo "--- got ---";      printf '%s\n' "$final_trail"
  exit 1
fi
