#!/usr/bin/env bash
# C38 SUPPORT — run every QA and security check before deployment.
#   bash bin/qa.sh [path/to/app/to/scan]
# Exits non-zero on the first failing stage.
set -euo pipefail
cd "$(dirname "$0")/.."
SCAN="${1:-templates}"

echo "== 1. PHP syntax lint"
fail=0
while IFS= read -r -d '' f; do php -l "$f" >/dev/null || { echo "  ✗ $f"; fail=1; }; done < <(find . -name '*.php' -not -path './vendor/*' -print0)
[ $fail -eq 0 ] && echo "  ✓ all PHP files lint clean" || exit 1

echo "== 2. Translation completeness (keys, placeholders, plurals, UTF-8, code scan: $SCAN)"
php bin/i18n-check.php "$SCAN"

echo "== 3. Checker self-test (must detect a broken language file)"
tmp="$(mktemp -d)"; cp -r . "$tmp/c38"; trap 'rm -rf "$tmp"' EXIT
php -r '$f=$argv[1]; $s=file_get_contents($f); $s=preg_replace("/\x27save\x27\s*=>\s*\x27[^\x27]*\x27,/u","",$s,1); $s=str_replace(":name",":nme",$s); file_put_contents($f,$s);' "$tmp/c38/languages/sv.php"
if php "$tmp/c38/bin/i18n-check.php" >/dev/null 2>&1; then echo "  ✗ checker missed injected errors"; exit 1; else echo "  ✓ checker detects missing keys / wrong placeholders"; fi

echo "== 4. Functional QA tests"
php tests/run.php | tail -1

echo "== 5. Security tests"
php tests/security.php | tail -1

echo "== 6. JavaScript syntax"
if command -v node >/dev/null; then node --check public/js/c38-i18n.js && echo "  ✓ c38-i18n.js parses"; else echo "  - node not installed, skipped"; fi

echo "== 7. Encoding: no BOM, UTF-8 only"
bad=0
while IFS= read -r -d '' f; do
  head -c3 "$f" | grep -q $'\xEF\xBB\xBF' && { echo "  ✗ BOM in $f"; bad=1; }
  iconv -f UTF-8 -t UTF-8 "$f" >/dev/null 2>&1 || { echo "  ✗ invalid UTF-8 in $f"; bad=1; }
done < <(find . -type f \( -name '*.php' -o -name '*.js' -o -name '*.sql' -o -name '*.md' \) -print0)
[ $bad -eq 0 ] && echo "  ✓ all files UTF-8 without BOM" || exit 1

echo
echo "ALL CHECKS PASSED"
