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

ROOT="${AGENTTEAM_MESSAGE_DELIVERY_INTENT_GUARDRAIL_ROOT:-$(git rev-parse --show-toplevel 2>/dev/null || pwd)}"
cd "$ROOT"

failures=0

fail() {
  printf 'FAIL: %s\n' "$1" >&2
  failures=$((failures + 1))
}

require_contains() {
  local file="$1"
  local pattern="$2"
  local message="$3"
  if [[ ! -f "$file" ]]; then
    fail "$message (missing $file)"
    return
  fi
  if ! rg -q -P -- "$pattern" "$file"; then
    fail "$message"
  fi
}

check_no_direct_production_outbox_composites() {
  local matches unexpected
  matches="$(rg -n -P \
    --glob '*.go' \
    --glob '!**/*_test.go' \
    -- '^\s*(?:return\s+)?(?:storemessage\.|message\.)?ScopeFanoutOutboxRecord\{' internal cmd desktop scripts 2>/dev/null || true)"
  unexpected="$(printf '%s\n' "$matches" | sed '/^$/d' | grep -v '^internal/store/message/scope_outbox_record.go:' || true)"
  if [[ -n "$unexpected" ]]; then
    fail "production scope fanout outbox rows must be built through the delivery intent builder"
    printf '%s\n' "$unexpected" >&2
  fi
}

check_no_direct_non_message_source_ref_fields() {
  local matches unexpected
  matches="$(rg -n -P \
    --glob '*.go' \
    --glob '!**/*_test.go' \
    -- 'EventRefType:\s*(?:DeliverySourceRefActivityEvent|"activity_event")|EventRefID:\s*[^,]+,' internal cmd desktop scripts 2>/dev/null || true)"
  unexpected="$(printf '%s\n' "$matches" | sed '/^$/d' | grep -v '^internal/store/message/scope_outbox_record.go:' || true)"
  if [[ -n "$unexpected" ]]; then
    fail "production non-message outbox event refs must be derived by BuildScopeDeliveryIntentOutboxRecord"
    printf '%s\n' "$unexpected" >&2
  fi
}

check_no_retired_workflow_handoff_runtime() {
  local matches
  matches="$(rg -n -P \
    --glob '*.go' \
    --glob '!**/*_test.go' \
    -- 'DeliverySourceRefWorkflowCommand|DeliveryAgentHandoffInternalWorkflow|delivery_agent_handoff|workflow_command|internal_workflow|SendInternalWorkflowMessageForUserWithMetadata|NotifyAgentInternalWorkflow' internal cmd desktop scripts 2>/dev/null || true)"
  if [[ -n "$matches" ]]; then
    fail "production code must not recreate the retired workflow_command/internal_workflow handoff"
    printf '%s\n' "$matches" >&2
  fi
}

require_contains \
  internal/store/message/scope_outbox_record.go \
  'type DeliveryIntent struct' \
  "typed DeliveryIntent handoff shape must remain in the message store boundary"

require_contains \
  internal/store/message/scope_outbox_record.go \
  'func BuildScopeDeliveryIntentOutboxRecord\(' \
  "canonical delivery intent outbox builder must exist"

require_contains \
  internal/store/message/scope_outbox_record.go \
  'BuildScopeDeliveryIntentOutboxRecord\(DeliveryIntent\{' \
  "message fanout wrapper must call the canonical delivery intent builder"

require_contains \
  internal/store/message/scope_outbox_payload.go \
  'type ScopeDeliveryIntentPayload struct' \
  "non-message delivery handoff payload must be typed and versioned"

require_contains \
  internal/api/im/fanout/scope_fanout_replay.go \
  'fanoutDeliveryIntentPayload' \
  "scope fanout replay must handle non-message delivery intent payloads explicitly"

require_contains \
  internal/api/im/fanout/fanout.go \
  'deliverDeliveryIntent' \
  "delivery fanout must expose a non-message agent/runtime handoff path"

require_contains \
  internal/store/message/scope_outbox_record_test.go \
  'TestBuildScopeMessageFanoutOutboxRecordWrapsDeliveryIntentBuilder' \
  "message wrapper compatibility must be covered by tests"

require_contains \
  internal/store/message/scope_outbox_record_test.go \
  'TestBuildScopeDeliveryIntentOutboxRecordForNonMessageSource' \
  "non-message delivery intent builder must be covered by tests"

require_contains \
  internal/api/im/fanout/scope_fanout_replay_task_test.go \
  'TestScopeFanoutReplayAdapterDeliversNonMessageIntentWithoutRealtime' \
  "non-message replay must prove it does not emit transcript realtime messages"

require_contains \
  internal/store/message/scope_applier.go \
  'validateMessagePlanScopeFanoutOutbox' \
  "message plan apply must guard message fanout source refs"

check_no_direct_production_outbox_composites
check_no_direct_non_message_source_ref_fields
check_no_retired_workflow_handoff_runtime

if (( failures > 0 )); then
  exit 1
fi

printf 'message delivery intent guardrails OK\n'
