#!/usr/bin/env bash
# v1.0 M4b dogfood seed scenario (ADR 033 D7). Populates a real DB with >=1 of
# every core class via REAL `zynk` producers, plus two clearly-named negative-
# reveal fixtures. Single source of truth for the acceptance suite + dogfooding.
# Expects a FRESH DB: the negative fixtures use fixed audit_ids (legacy01,
# noretain01), so re-running into an already-populated DB fails (duplicate audit_id).
set -euo pipefail

: "${ZYNK_BIN:?set ZYNK_BIN}"
: "${DB:?set DB}"
: "${ROOT:?set ROOT}"
: "${SESSION_ID:=s1}"
: "${WORKSPACE_ID:=w-test}"
: "${HERDR_BIN:=herdr}"
: "${CUSTODY_KEY_FILE:=${DB%/*}/custody.key}"

mkdir -p "$(dirname "$DB")" "$ROOT"
z() { "$ZYNK_BIN" "$@"; }
base=(--root "$ROOT" --db "$DB" --session-id "$SESSION_ID")
report_base=(--root "$ROOT" --db "$DB" --session-id "$SESSION_ID" --actor claude)

z db --db "$DB" init

z status --timestamp "2026-05-31T00:00:00Z" --phase plan --mode brainstorm \
  --artifact-ref ref-1 --lead-agent codex --status working \
  --completed c --in-progress i --next-action n --blockers none \
  --asks-for-zevs none --risk none --expected-wait unknown "${base[@]}"

# gate + conflict FIRST => work_events 1 and 2 (deterministic --ref 1/2).
z report gate --title "Approve plan" --summary ready --proposer claude \
  --action Approve --action "Request changes" "${report_base[@]}"
z report conflict --topic "Limiter algorithm" \
  --position "claude:token-bucket:absorbs bursts:tunable refill" \
  --recommended token-bucket --option token-bucket --option fixed-window "${report_base[@]}"
z report think --text "weighing options" "${report_base[@]}"
z report tool --name run_tests --arg "cargo test" --output "12 passing" --ok "${report_base[@]}"
z report plan --title "Token-bucket limiter" --item "atomic Lua" --item "tiered limits" "${report_base[@]}"
z report artifact --file "src/rateLimit.js:96:1" "${report_base[@]}"
z report usage --agent claude --tokens 4700 "${report_base[@]}"
z report system --text "merged · CI green" "${report_base[@]}"
z report diff --file "src/rateLimit.js" --added 12 --removed 3 \
  --hunk "add:+ const bucket = new TokenBucket()" "${report_base[@]}"

z decide gate     --ref 1 --verdict approve            "${base[@]}"
z decide conflict --ref 2 --resolution "use mutex"     "${base[@]}"
z decide mode     --to review                          "${base[@]}"
z decide interrupt --reason "pause for review"         "${base[@]}"
z decide redirect --to codex --reason handoff          "${base[@]}"

# Messages via real audited send (hermetic via $HERDR_BIN stub).
# Audited send (ADR 029 C2): --pane must equal the address half of --to. Also,
# request-action requires --due per tools/message-profile.yaml per_type_required_fields.
z send herdr --pane "$WORKSPACE_ID-2" --herdr-bin "$HERDR_BIN" \
  --session-id "$SESSION_ID" --from "operator:$WORKSPACE_ID-0" \
  --to "claude:$WORKSPACE_ID-2" --mid task01 --type request-action \
  --due "2026-06-01T00:00:00Z" \
  --payload-redaction-policy full --body "Implement the token-bucket limiter." \
  --command-origin operator --root "$ROOT" --db "$DB"
z send herdr --pane "$WORKSPACE_ID-1" --herdr-bin "$HERDR_BIN" \
  --session-id "$SESSION_ID" --from "claude:$WORKSPACE_ID-2" \
  --to "codex:$WORKSPACE_ID-1" --mid disc01 --type status-update \
  --payload-redaction-policy full --body "Limiter drafted; please review." \
  --root "$ROOT" --db "$DB"

# Hash-only RETAINED (revealable) record via a REAL audited send (spec D1): a real
# redacted MESSAGE — both the visible (hash-only corpus) and reveal states proven,
# same `send herdr` producer as the other messages (--pane == --to address half).
# send herdr auto-mints the audit_id, so capture it from the written audit.md (the
# block whose mid=rvl01) for the reveal; no extra dependency.
z send herdr --pane "$WORKSPACE_ID-1" --herdr-bin "$HERDR_BIN" \
  --session-id "$SESSION_ID" --from "claude:$WORKSPACE_ID-2" \
  --to "codex:$WORKSPACE_ID-1" --mid rvl01 --type status-update \
  --payload-redaction-policy hash-only --retain-custody \
  --custody-key-file "$CUSTODY_KEY_FILE" \
  --body "sensitive: API_KEY=redacted-secret" --root "$ROOT" --db "$DB"
# Parse the auto-minted audit_id: remember the most recent `audit_id=` line, emit it
# at the `mid=rvl01` block (END prints the last such match — robust to re-runs).
revealed_id=$(awk -F= '/^audit_id=/{cur=$2} /^mid=rvl01$/{found=cur} END{print found}' \
  "$ROOT/sessions/$SESSION_ID/audit.md")
: "${revealed_id:?failed to capture the rvl01 audit_id from audit.md}"
z reveal "$revealed_id" --root "$ROOT" --db "$DB" --custody-key-file "$CUSTODY_KEY_FILE" \
  --actor zevs --timestamp "2026-05-31T03:05:00Z"

# Two NAMED negative-reveal fixtures (both lack a custody vault => not revealable).
# FIXTURE A — legacy hash-only (no custody retained) -> not revealable.
z audit --audit-id legacy01 --timestamp "2026-05-31T03:10:00Z" \
  --source-agent claude --source-address "$WORKSPACE_ID-2" \
  --target-agent codex --target-address "$WORKSPACE_ID-1" \
  --transport herdr --workspace-id "$WORKSPACE_ID" --mid legacymid \
  --type status-update --command-origin agent \
  --delivery-status observed --observed-by claude --verified-by helper-tool \
  --payload-redaction-policy hash-only --payload "legacy redacted content" "${base[@]}"
# FIXTURE B — no-retain full-policy record -> never custodied / irrecoverable as ciphertext.
z audit --audit-id noretain01 --timestamp "2026-05-31T03:20:00Z" \
  --source-agent claude --source-address "$WORKSPACE_ID-2" \
  --target-agent codex --target-address "$WORKSPACE_ID-1" \
  --transport herdr --workspace-id "$WORKSPACE_ID" --mid noretainmid \
  --type status-update --command-origin agent \
  --delivery-status observed --observed-by claude --verified-by helper-tool \
  --payload-redaction-policy full --payload "no-retain content" "${base[@]}"

echo "seed-scenario complete: session=$SESSION_ID db=$DB"
