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

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

warn() {
  echo "[WARN] $*"
}

# Blocking baseline
bin/qa-required.sh

# QG-004 (non-blocking in phase 1): structural checks as warning-only signal
if command -v rg >/dev/null 2>&1; then
  c1="$( (rg 'new\\s+[^\\s(]+Factory\\(' core/Service || true) | wc -l | tr -d '[:space:]')"
  c2="$( (rg --glob '!**/*Factory.php' 'new\\s+[^\\s(]+(Service|Gateway|Repository)\\(' core/Service || true) | wc -l | tr -d '[:space:]')"
  c3="$( (rg "\\b(accessServicesFactory|directoryServicesFactory|userServicesFactory|authServicesFactory|tenantServicesFactory|settingServicesFactory|userRepositoryFactory|authRepositoryFactory|authGatewayFactory)\\(" pages core templates web || true) | wc -l | tr -d '[:space:]')"
  c4="$( (rg -n 'new\\s+[^\\s(]+(Service|Gateway|Repository)\\(' pages -g '*.php' || true) | wc -l | tr -d '[:space:]')"
  c5="$( (rg -n '\\bDB::' pages -g '*.php' || true) | wc -l | tr -d '[:space:]')"
  c6="$( (rg -n 'app\\([^\\n]*Factory::class\\)->create' pages/admin -g '*.php' || true) | wc -l | tr -d '[:space:]')"
  c7="$( (rg -n 'Factory::class' pages/admin -g '*.php' || true) | wc -l | tr -d '[:space:]')"
  c8="$( (rg -n 'ApiResponse::readJsonBody\\(' pages/api/v1 -g '*.php' || true) | wc -l | tr -d '[:space:]')"

  if [[ "${c1}" == "0" && "${c2}" == "0" && "${c3}" == "0" && "${c4}" == "0" && "${c5}" == "0" && "${c6}" == "0" && "${c7}" == "0" && "${c8}" == "0" ]]; then
    echo "[OK]   QG-004 Structural checks clean"
  else
    warn "QG-004 Structural checks found potential violations (non-blocking): ${c1}/${c2}/${c3}/${c4}/${c5}/${c6}/${c7}/${c8}"
  fi
else
  warn "QG-004 skipped: rg is not installed"
fi

# QG-007 (non-blocking): periodic dependency hygiene
if docker compose exec -T php vendor/bin/composer-unused; then
  echo "[OK]   QG-007 composer-unused"
else
  warn "QG-007 composer-unused reported issues (non-blocking in phase 1)"
fi

# QG-005 (manual, non-blocking)
warn "QG-005 manual step required: Browser smoke with DevTools console (expect no new JS errors)."

echo "[OK] Extended QA completed (required gates already passed, optional gates reported)."
