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

ROOT="${AGENTTEAM_MESSAGE_NON_TASK_LEGACY_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_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; Workflow Run effects write ordinary visible messages with native workflow_run source and WorkflowContext callback metadata"
    printf '%s\n' "$matches" >&2
  fi
}

check_no_system_card_write_payloads() {
  local matches
  matches="$(rg -n -P \
    --glob '*.go' \
    --glob '!**/*_test.go' \
    --glob '!internal/store/app/app_notification_policy.go' \
    -- '"card"[[:space:]]*:' internal/store/app internal/api internal/service 2>/dev/null || true)"
  if [[ -n "$matches" ]]; then
    fail "production app/api/service code must not construct metadata.card system-card payloads"
    printf '%s\n' "$matches" >&2
  fi
}

require_contains \
  guardrails/message/non-task-legacy-inventory.md \
  "message_type = 'internal_workflow'" \
  "non-task legacy inventory must track the retired internal_workflow handoff"

require_contains \
  guardrails/message/non-task-legacy-inventory.md \
  "message_type = 'internal_automation'" \
  "non-task legacy inventory must track the historical hidden transcript envelope"

require_contains \
  guardrails/message/non-task-legacy-inventory.md \
  'metadata\.card\.kind' \
  "non-task legacy inventory must track retired system-card metadata"

require_contains \
  guardrails/message/non-task-legacy-inventory.md \
  'task_dispatch' \
  "non-task legacy inventory must explicitly defer task-owned message shapes"

require_contains \
  internal/store/message/message_types_test.go \
  'TestPreTaskNonTaskLegacySemanticsAreClosed' \
  "pre-task non-task legacy descriptors must have closed-write coverage"

require_contains \
  internal/tidb/migrations/00160_non_task_legacy_message_cleanup.sql \
  '`message_type` = '\''internal_automation'\''' \
  "non-task legacy cleanup migration must delete retained internal_automation rows"

require_contains \
  internal/tidb/migrations/00160_non_task_legacy_message_cleanup.sql \
  'DELETE[[:space:]]+outbox' \
  "non-task legacy cleanup migration must delete legacy internal_workflow outbox rows"

require_contains \
  internal/tidb/migrations/00160_non_task_legacy_message_cleanup.sql \
  'agentteam_non_task_legacy_message_cleanup_request_ids' \
  "non-task legacy cleanup migration must capture legacy request ids before clearing jobs"

require_contains \
  internal/tidb/migrations/00160_non_task_legacy_message_cleanup.sql \
  'legacy_internal_automation_removed' \
  "non-task legacy cleanup migration must fail stale active jobs tied to deleted internal_automation rows"

require_contains \
  internal/store/app/app_messages_integration_test.go \
  'TestSendInternalWorkflowMessageTypeIsRetiredForActiveWrites' \
  "canonical app message append must reject internal_workflow active writes"

require_contains \
  internal/store/app/message_append.go \
  'CurrentWriteAllowed\(\)' \
  "canonical append boundary must enforce semantics current-write policy"

require_contains \
  internal/store/app/message_append.go \
  'SystemCardKind\(options\.Metadata\) != ""' \
  "canonical append boundary must reject retired system-card writes"

require_contains \
  internal/store/message/message_types_test.go \
  'TestNoRegisteredSystemCardSemanticsRemain' \
  "retired system-card read fallback must stay deleted"

require_contains \
  internal/store/message/message_types_test.go \
  'IsRegisteredMessageType\("internal_workflow"\)' \
  "internal_workflow storage type must remain unregistered in message semantics"

require_contains \
  internal/store/message/scope_outbox_payload_test.go \
  'TestScopeDeliveryIntentPayloadRejectsRetiredWorkflowCommandSource' \
  "delivery intent payloads must reject the retired workflow_command source ref"

if rg -q 'embedded_task' guardrails/message/non-task-legacy-inventory.md; then
  fail "non-task legacy inventory must not retain embedded_task read fallback wording"
fi

check_no_retired_workflow_handoff_runtime
check_no_system_card_write_payloads

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

printf 'non-task legacy message guardrail OK\n'
