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

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd -P)"
dto_root="${STORE_REFACTOR_API_DTO_ROOT:-${repo_root}/internal/api/dto}"
max_refs="${STORE_REFACTOR_MAX_API_DTO_STORE_REFS:-0}"

if ! command -v rg >/dev/null 2>&1; then
  echo "error: ripgrep (rg) is required" >&2
  exit 127
fi
if [[ ! -d "${dto_root}" ]]; then
  echo "error: API DTO root does not exist: ${dto_root}" >&2
  exit 2
fi

matches="$(rg 'github\.com/tidbcloud/AgentTeam/internal/store' "${dto_root}" --glob '*.go' 2>/dev/null | grep -v '/converter/' || true)"
if [[ -z "${matches}" ]]; then
  actual_refs=0
else
  actual_refs="$(printf '%s\n' "${matches}" | wc -l | tr -d '[:space:]')"
fi

printf 'internal/api/dto store refs (target 0): %s (max %s)\n' "${actual_refs}" "${max_refs}"
if (( actual_refs > max_refs )); then
  echo "error: internal/api/dto store refs (target 0) increased above allowed baseline (${actual_refs} > ${max_refs})" >&2
  exit 1
fi
