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

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

python3 - <<'PY'
from pathlib import Path
import re

# These tables remain migration/history input only. Runtime Go, including
# runtime tests and fixtures, must use the canonical Service Actor, Service
# Event, notification, and provider stores. TiDB migration/bootstrap/admin
# inventory is intentionally outside this guardrail's ownership.
legacy_tables = (
    "apps",
    "app_versions",
    "app_installations",
    "app_connections",
    "app_grants",
    "agent_app_authorizations",
    "target_app_bindings",
    "app_webhook_deliveries",
    "workspace_app_catalog_attributions",
    "workspace_app_managers",
    "app_notifications",
    "app_notification_mutations",
    "scope_app_notification_cards",
    "app_notification_actions",
    "app_trigger_rate_limit_events",
    "github_app_config",
    "gitea_app_config",
    "github_app_workspace_claims",
)
name_pattern = "|".join(re.escape(name) for name in legacy_tables)
table_ref = re.compile(
    rf"\b(?i:from|join|into|update|references|table)\s+[`\"']?(?:{name_pattern})[`\"']?\b"
)

matches: list[str] = []
for path in sorted(Path(".").rglob("*.go")):
    rel = path.as_posix()
    if (
        rel.startswith("internal/tidb/")
        or rel.startswith("x/")
        or rel.startswith("vendor/")
        or rel.startswith(".git/")
        or "/.git/" in rel
    ):
        continue
    for line_number, line in enumerate(path.read_text(errors="ignore").splitlines(), 1):
        if table_ref.search(line):
            matches.append(f"{rel}:{line_number}: {line.strip()}")

if matches:
    print("canonical App runtime guardrail: legacy App table SQL references found:", flush=True)
    print("\n".join(matches), flush=True)
    raise SystemExit(1)

print("canonical App runtime guardrail: no legacy App table SQL references")
PY
