#!/usr/bin/env bash
set -euo pipefail

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)"
render="$repo_root/ai/tools/operator-notifications/render-event.mjs"
send_event="$repo_root/ai/tools/operator-notifications/send-event.sh"

"$repo_root/ai/runtime/start-daemon.sh" >/dev/null

assert_contains() {
  local haystack="$1" needle="$2" label="$3"
  [[ "$haystack" == *"$needle"* ]] || {
    printf 'FAIL: %s\nExpected to contain: %s\nActual:\n%s\n' "$label" "$needle" "$haystack" >&2
    exit 1
  }
}

assert_not_contains() {
  local haystack="$1" needle="$2" label="$3"
  [[ "$haystack" != *"$needle"* ]] || {
    printf 'FAIL: %s\nDid not expect: %s\nActual:\n%s\n' "$label" "$needle" "$haystack" >&2
    exit 1
  }
}

note="$("$render" --class runtime_note --title "Runtime note" --message "Bridge restart verified." --next "Continue validation.")"
assert_contains "$note" "Runtime note" "runtime note renders title"
assert_contains "$note" "Next: Continue validation." "runtime note renders next"
assert_not_contains "$note" "Reply" "runtime note does not request reply"
assert_not_contains "$note" "freeform" "runtime note does not request freeform"

api_note="$(AI_RUNTIME_WRAPPER_MODE=required "$render" --format json --class runtime_note --title "Runtime note" --message "Runtime Core render verified.")"
assert_contains "$api_note" '"source": "runtime-core-cli"' "runtime core facade renders through canonical CLI"
assert_contains "$api_note" '"may_request_freeform": false' "runtime core render preserves actionability"

legacy_note="$(AI_RUNTIME_WRAPPER_MODE=legacy "$render" --format json --class runtime_note --title "Runtime note" --message "Legacy mode remains cut over.")"
assert_contains "$legacy_note" '"source": "runtime-core-cli"' "legacy wrapper mode does not restore duplicated shell rendering"

if "$render" --class governance_note --title "Governance note" --message "Reply with freeform text." >/tmp/operator-note-invalid.out 2>&1; then
  echo "FAIL: governance note must reject freeform wording" >&2
  exit 1
fi
assert_contains "$(cat /tmp/operator-note-invalid.out)" "must not request freeform" "non-freeform note rejects freeform wording"

approval="$("$render" --class approval_required --title "Close reviewed chunk?" --message "Approval creates an approved-action record.")"
assert_contains "$approval" "approved-action" "approval message uses approval-specific wording"
assert_not_contains "$approval" "freeform" "approval message does not request freeform"

dry="$("$send_event" --dry-run --class architectural_note --title "Architecture note" --message "Dispatcher owns execution.")"
assert_contains "$dry" "Architecture note" "send-event dry-run renders note"
assert_not_contains "$dry" "Reply" "send-event note has no reply block"

echo "Operator notification tests passed."
