#!/usr/bin/env bash
# Hard QA gate for the gemma-data-team agent team.
#
# Fires on TaskCompleted. Blocks completion (exit 2) of *data* tasks when either:
#   1. block-until-Bedrock: the team is NOT on Bedrock, so full dbt parse/build/show
#      verification could not have run — the work cannot be trusted as done; or
#   2. no QA sign-off: the qa-auditor has not appended the QA-PASS token to the task.
#
# Non-data tasks (and tasks already carrying QA-PASS while on Bedrock) pass through.
# The check is intentionally heuristic and schema-tolerant: it flattens whatever JSON
# the TaskCompleted payload provides and scans the text, so it keeps working even if
# the payload shape changes. Exit 0 = allow, exit 2 = block with feedback on stderr.

set -uo pipefail

input="$(cat)"

# Flatten all string values from the payload into one lowercase blob. Fall back to the
# raw input if jq is unavailable or the payload isn't valid JSON.
if command -v jq >/dev/null 2>&1; then
  blob="$(printf '%s' "$input" | jq -r '[.. | strings] | join(" ")' 2>/dev/null)"
fi
[ -n "${blob:-}" ] || blob="$input"
low="$(printf '%s' "$blob" | tr '[:upper:]' '[:lower:]')"

# Is this a data task? Match discipline tags or data-stack vocabulary.
# The discipline tags ([de]/[ae]/[da]/[ds]) the ticket-fetcher always applies are the
# primary signal; the vocabulary is a secondary net. A few terms (load/schema/model) are
# deliberately broad: a false positive only DEFERS completion of a non-data task (the safe
# direction), whereas narrowing them risks the worse failure — letting an unverified data
# task close without QA/Bedrock verification.
data_re='(\[(de|ae|da|ds)\]|(^|[^a-z])(de|ae|da|ds):|dbt|dlt|airflow|connector|pipeline|warehouse|snowflake|bigquery|\bmodel\b|\bmodels\b|dimension|fact table|\bmart\b|\bmarts\b|metric|lightdash|metabase|\bsql\b|ingest|extract|\bload\b|\bschema\b|forecast|statistic|regression|time[ .-]?series|machine.learning|notebook|pandas|scikit|statsmodels|prophet)'

if ! printf '%s' "$low" | grep -Eq "$data_re"; then
  # Not a data task — the gate does not apply.
  exit 0
fi

on_bedrock=0
[ "${CLAUDE_CODE_USE_BEDROCK:-}" = "1" ] && on_bedrock=1

has_signoff=0
# Require the structured token "QA-PASS:" (colon-suffixed), matched case-insensitively
# as a standalone token. A bare mention of "qa-pass" in a task title/description does
# not count — only the auditor's deliberate "QA-PASS: <rationale>" sign-off opens the gate.
printf '%s' "$low" | grep -Eq '(^|[^a-z])qa-pass:' && has_signoff=1

if [ "$on_bedrock" -ne 1 ]; then
  echo "QA gate (block-until-Bedrock): this is a data task, but the team is running on the Anthropic API where dbt build/test/show and warehouse queries cannot run. Full verification was not possible, so the task cannot be marked complete. Switch the team to Bedrock (bedrock-on / claude-db) and re-verify, then let the qa-auditor sign off." >&2
  exit 2
fi

if [ "$has_signoff" -ne 1 ]; then
  echo "QA gate: this data task has no qa-auditor sign-off. The qa-auditor must run its baseline (validate-repo + Kimball + Gemma SQL style), reach a PASS verdict, and append the token 'QA-PASS:' (with a one-line rationale) to the task before it can be completed." >&2
  exit 2
fi

exit 0
