#!/usr/bin/env bash
# next/tests/outbox_publish.sh — Step 6d-publish acceptance test.
#
# Exercises outbox:publish/2 across the happy path, sig failure,
# replay halt, and envelope-shape failure. Returns shape:
#   {ok, [{cid, _}, {activity, _}], NewLogState}
#   {error, Reason, LogState}
# 10 cases.

set -uo pipefail
cd "$(git rev-parse --show-toplevel)"

SX_SERVER="${SX_SERVER:-hosts/ocaml/_build/default/bin/sx_server.exe}"
if [ ! -x "$SX_SERVER" ]; then
  SX_SERVER="/root/rose-ash/hosts/ocaml/_build/default/bin/sx_server.exe"
fi
if [ ! -x "$SX_SERVER" ]; then
  echo "ERROR: sx_server.exe not found." >&2
  exit 1
fi

VERBOSE="${1:-}"
PASS=0; FAIL=0; ERRORS=""
TMPFILE=$(mktemp); trap "rm -f $TMPFILE" EXIT

# Shared prelude builds a fresh actor state, key spec, empty log,
# and a context proplist. Each test inlines it.
PRELUDE='KM = <<1,2,3,4>>, KS = [{key_id,k1},{algorithm,ed25519},{value,KM}], AS = [{public_keys,[[{id,k1},{created,50},{value,KM}]]}], {ok, L0} = log:open(alice, base), Ctx = [{actor_id,alice},{published,100},{key_spec,KS},{actor_state,AS},{log,L0}], Req = [{type,create},{object,nil}],'

cat > "$TMPFILE" <<EPOCHS
(epoch 1)
(load "lib/erlang/tokenizer.sx")
(load "lib/erlang/parser.sx")
(load "lib/erlang/parser-core.sx")
(load "lib/erlang/parser-expr.sx")
(load "lib/erlang/parser-module.sx")
(load "lib/erlang/transpile.sx")
(load "lib/erlang/runtime.sx")
(load "lib/erlang/vm/dispatcher.sx")

(epoch 2)
(eval "(get (erlang-load-module (file-read \"next/kernel/envelope.erl\")) :name)")
(epoch 3)
(eval "(get (erlang-load-module (file-read \"next/kernel/log.erl\")) :name)")
(epoch 4)
(eval "(get (erlang-load-module (file-read \"next/kernel/pipeline.erl\")) :name)")
(epoch 5)
(eval "(get (erlang-load-module (file-read \"next/kernel/outbox.erl\")) :name)")

;; Happy path: publish returns {ok, Result, NewLog}, log tip advances
(epoch 10)
(eval "(get (erlang-eval-ast \"${PRELUDE} case outbox:publish(Req, Ctx) of {ok, _, NewLog} -> log:tip(NewLog) =:= 1; _ -> false end\") :name)")

;; Result has :cid pointing at the activity's CID
(epoch 11)
(eval "(get (erlang-eval-ast \"${PRELUDE} {ok, Result, _} = outbox:publish(Req, Ctx), {ok, Cid} = envelope:get_field(cid, Result), {ok, Act} = envelope:get_field(activity, Result), outbox:cid_of(Act) =:= Cid\") :name)")

;; The signed activity is in the log
(epoch 12)
(eval "(get (erlang-eval-ast \"${PRELUDE} {ok, Result, NewLog} = outbox:publish(Req, Ctx), {ok, Act} = envelope:get_field(activity, Result), log:entries(NewLog) =:= [Act]\") :name)")

;; Replay: second publish of identical Request halts the pipeline
(epoch 13)
(eval "(get (erlang-eval-ast \"${PRELUDE} {ok, _, L1} = outbox:publish(Req, Ctx), Ctx2 = [{actor_id,alice},{published,100},{key_spec,KS},{actor_state,AS},{log,L1}], case outbox:publish(Req, Ctx2) of {error, replay, _} -> ok; _ -> bad end\") :name)")

;; Replay returns the pre-append LogState unchanged
(epoch 14)
(eval "(get (erlang-eval-ast \"${PRELUDE} {ok, _, L1} = outbox:publish(Req, Ctx), Ctx2 = [{actor_id,alice},{published,100},{key_spec,KS},{actor_state,AS},{log,L1}], {error, _, L2} = outbox:publish(Req, Ctx2), log:tip(L2) =:= 1\") :name)")

;; Bad key material (sig fails) -> {error, bad_signature, LogState}
(epoch 15)
(eval "(get (erlang-eval-ast \"${PRELUDE} OtherKM = <<9,9,9,9>>, BadKS = [{key_id,k1},{algorithm,ed25519},{value,OtherKM}], BadCtx = [{actor_id,alice},{published,100},{key_spec,BadKS},{actor_state,AS},{log,L0}], case outbox:publish(Req, BadCtx) of {error, bad_signature, _} -> ok; _ -> bad end\") :name)")

;; Distinct timestamps -> two activities in log
(epoch 16)
(eval "(get (erlang-eval-ast \"${PRELUDE} {ok, _, L1} = outbox:publish(Req, Ctx), Ctx2 = [{actor_id,alice},{published,200},{key_spec,KS},{actor_state,AS},{log,L1}], {ok, _, L2} = outbox:publish(Req, Ctx2), log:tip(L2) =:= 2\") :name)")

;; Distinct types -> distinct CIDs
(epoch 17)
(eval "(get (erlang-eval-ast \"${PRELUDE} {ok, R1, L1} = outbox:publish(Req, Ctx), R2 = [{type,update},{object,nil}], Ctx2 = [{actor_id,alice},{published,100},{key_spec,KS},{actor_state,AS},{log,L1}], {ok, R, _} = outbox:publish(R2, Ctx2), {ok, C1} = envelope:get_field(cid, R1), {ok, C2} = envelope:get_field(cid, R), C1 =/= C2\") :name)")

;; CID stable: same Request twice (across fresh logs) -> same CID
(epoch 18)
(eval "(get (erlang-eval-ast \"${PRELUDE} {ok, R1, _} = outbox:publish(Req, Ctx), {ok, L0b} = log:open(alice, base), Ctx_b = [{actor_id,alice},{published,100},{key_spec,KS},{actor_state,AS},{log,L0b}], {ok, R2, _} = outbox:publish(Req, Ctx_b), {ok, C1} = envelope:get_field(cid, R1), {ok, C2} = envelope:get_field(cid, R2), C1 =:= C2\") :name)")
EPOCHS

OUTPUT=$(timeout 240 "$SX_SERVER" < "$TMPFILE" 2>/dev/null)

check() {
  local epoch="$1" desc="$2" expected="$3"
  local actual
  actual=$(echo "$OUTPUT" | awk -v e="$epoch" '
    $0 ~ "^\\(ok-len " e " " { getline; print; exit }
    $0 ~ "^\\(ok " e " "     { print; exit }
    $0 ~ "^\\(error " e " "  { print; exit }
  ')
  [ -z "$actual" ] && actual="<no output for epoch $epoch>"
  if echo "$actual" | grep -qF -- "$expected"; then
    PASS=$((PASS+1))
    [ "$VERBOSE" = "-v" ] && echo "  ok $desc"
  else
    FAIL=$((FAIL+1))
    ERRORS+="  FAIL [$desc] (epoch $epoch) expected: $expected | actual: $actual
"
  fi
}

check  2  "envelope module loaded"             "envelope"
check  3  "log module loaded"                  "log"
check  4  "pipeline module loaded"             "pipeline"
check  5  "outbox module loaded"               "outbox"
check 10  "happy path tip advances to 1"       "true"
check 11  "result :cid matches activity"       "true"
check 12  "signed activity in log entries"     "true"
check 13  "duplicate publish -> replay"        "ok"
check 14  "replay leaves log tip at 1"         "true"
check 15  "bad key material -> bad_signature"  "ok"
check 16  "distinct timestamps -> tip 2"       "true"
check 17  "distinct types -> distinct CIDs"    "true"
check 18  "same request -> same CID"           "true"

TOTAL=$((PASS+FAIL))
if [ $FAIL -eq 0 ]; then
  echo "ok $PASS/$TOTAL next/tests/outbox_publish.sh passed"
else
  echo "FAIL $PASS/$TOTAL passed, $FAIL failed:"
  echo "$ERRORS"
fi
[ $FAIL -eq 0 ]
