#!/usr/bin/env bash
set -euo pipefail
LIB="$(cd "$(dirname "$0")" && pwd)/journal.sh"
PASS=0; FAIL=0
ok() { PASS=$((PASS+1)); printf '  ok   %s\n' "$1"; }
bad() { FAIL=$((FAIL+1)); printf '  FAIL %s\n     %s\n' "$1" "$2"; }

printf 'journal.sh tests:\n'
tmpdir=$(mktemp -d)
trap 'rm -rf "$tmpdir"' EXIT
journal="$tmpdir/events.jsonl"
record='{"task":"t1","state":"ready","ts":"2026-08-09T00:00:00Z"}'

if bash "$LIB" append "$journal" "$record" && [[ "$(cat "$journal")" == "$record" ]]; then
  ok "append persists a JSON record"
else
  bad "append persists a JSON record" "unexpected journal contents"
fi

if [[ "$(bash "$LIB" state "$journal" t1)" == "ready" ]]; then
  ok "state returns the latest state for a task"
else
  bad "state returns the latest state for a task" "wrong state"
fi

if bash "$LIB" append "$journal" '{invalid' >/dev/null 2>&1; then
  bad "append rejects invalid JSON" "expected failure"
else
  ok "append rejects invalid JSON"
fi

if bash "$LIB" append "$journal" '{"formatVersion":2}' >/dev/null 2>&1; then
  bad "append rejects unsupported format version" "expected failure"
else
  ok "append rejects unsupported format version"
fi

printf '\nPassed: %d  Failed: %d\n' "$PASS" "$FAIL"
[[ $FAIL -eq 0 ]]
