#!/usr/bin/env bash
#
# vendor-check — gate de vendorização e licenças (ADR-002, plano 05 §3.3).
#
# 1. Falha se houver asset/CDN externo **fora da allowlist fechada** do projeto.
# 2. Valida as licenças de composer.lock contra a allowlist permissiva.
#
# ALLOWLIST (ADR-002) — as ÚNICAS requisições externas aceitas pelo projeto:
#   - vlibras.gov.br                → acessibilidade oficial (gov.br), carregada sob demanda
#   - googletagmanager.com          → Google Analytics, opt-in (só com ID no painel de suporte)
#   - google-analytics.com          → Google Analytics (beacon)
# Qualquer outro domínio externo FALHA o build. A allowlist só muda com ADR própria.
#
# Uso: tools/vendor-check.sh [RAIZ]
set -Eeuo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
[ "${1:-}" != "" ] && ROOT="$1"

ALLOWED='vlibras\.gov\.br|googletagmanager\.com|google-analytics\.com'

# CDNs conhecidos + qualquer asset externo em <script>/<link>/<img>/<iframe> **ou**
# atribuição em JS (`script.src = 'https://…'`, `href: "https://…"`).
PATTERN='cdnjs\.cloudflare|unpkg\.com|jsdelivr\.net|fonts\.googleapis|ajax\.googleapis|<(script|link|img|iframe)[^>]+(src|href)=["'"'"']https?://|(src|href)\s*[=:]\s*["'"'"'`]https?://'

rc=0
allowed_hits=0
violations=()

mapfile -t dirs < <(printf '%s\n' "$ROOT/src" "$ROOT/resources" "$ROOT/public" | while read -r d; do [ -d "$d" ] && echo "$d"; done)

if [ "${#dirs[@]}" -gt 0 ]; then
    mapfile -t matched < <(grep -rIlE \
        --include='*.blade.php' --include='*.js' --include='*.ts' --include='*.css' --include='*.html' \
        --exclude-dir=Test --exclude-dir=tests --exclude-dir=build --exclude-dir=node_modules \
        --exclude-dir=report --exclude-dir=test-results --exclude-dir=.vite \
        "$PATTERN" "${dirs[@]}" 2>/dev/null | sort || true)

    for file in "${matched[@]}"; do
        # Referências na allowlist (VLibras/GA) são permitidas; o resto é violação.
        allowed_hits=$((allowed_hits + $(grep -cE "$ALLOWED" "$file" 2>/dev/null || true)))

        while IFS= read -r hit; do
            violations+=("${file#"$ROOT"/}:${hit}")
        done < <(grep -nE "$PATTERN" "$file" 2>/dev/null | grep -vE "$ALLOWED" || true)
    done
fi

if [ "${#violations[@]}" -gt 0 ]; then
    printf '%s\n' "${violations[@]}" >&2
    echo "ERRO: domínio externo fora da allowlist (ADR-002: só VLibras + Google Analytics opt-in)." >&2
    rc=1
fi

# Licenças (composer.lock). Usa o PHP do ambiente.
if [ -f "$ROOT/composer.lock" ] && command -v php >/dev/null 2>&1; then
    php "$ROOT/tools/licenses-check.php" "$ROOT" || rc=1
elif [ ! -f "$ROOT/composer.lock" ]; then
    echo "AVISO: composer.lock ausente — pulando a checagem de licenças." >&2
else
    echo "AVISO: php indisponível — pulando a checagem de licenças." >&2
fi

[ "$allowed_hits" -gt 0 ] && echo "allowlist (ADR-002): $allowed_hits referência(s) a VLibras/Google Analytics."

if [ "$rc" -ne 0 ]; then
    echo "vendor-check: FALHOU" >&2
    exit 1
fi

echo "vendor-check: OK"
exit 0
