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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT_DIR"

if ! command -v rg >/dev/null 2>&1; then
  echo "ERROR: ripgrep (rg) is required for td-guard checks."
  exit 1
fi

changed_files=()
while IFS= read -r file; do
  changed_files+=("$file")
done < <(
  {
    git diff --name-only --diff-filter=ACMRTUXB HEAD
    git ls-files --others --exclude-standard
  } | awk 'NF' | awk '!seen[$0]++'
)

td_targets=()
for file in "${changed_files[@]}"; do
  case "$file" in
    sections/td-*.liquid|blocks/td-*.liquid|blocks/_td-*.liquid|snippets/td-*.liquid)
      if [[ -f "$file" ]]; then
        td_targets+=("$file")
      fi
      ;;
  esac
done

if [[ "${#td_targets[@]}" -eq 0 ]]; then
  echo "td-guard: no changed TD liquid files to validate."
  exit 0
fi

schema_default_pattern='(section|block)\.settings\.[A-Za-z0-9_]+\s*\|\s*default\s*:'

schema_default_hits="$(rg -n --pcre2 "$schema_default_pattern" "${td_targets[@]}" || true)"
if [[ -n "$schema_default_hits" ]]; then
  echo "td-guard: FAIL - redundant schema fallback detected in changed TD files."
  echo "Rule: do not use '| default:' with schema-backed section/block settings."
  echo ""
  echo "$schema_default_hits"
  exit 1
fi

echo "td-guard: PASS"
