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

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

run_step() {
  local label="$1"
  shift
  echo "[RUN] ${label}"
  "$@"
  echo "[OK]  ${label}"
}

if ! command -v docker >/dev/null 2>&1; then
  echo "[ERROR] docker is required." >&2
  exit 2
fi

docker compose version >/dev/null 2>&1 || {
  echo "[ERROR] docker compose is required." >&2
  exit 2
}

run_step "QG-001 PHPUnit" \
  docker compose exec -T php vendor/bin/phpunit

run_step "QG-002 PHPStan" \
  docker compose exec -T php vendor/bin/phpstan analyse -c phpstan.neon --no-progress

run_step "QG-003 Architecture Core Contract" \
  docker compose exec -T php vendor/bin/phpunit tests/Architecture/CoreStarterkitContractTest.php

run_step "QG-006 PHP Style Check" \
  docker compose exec -T php vendor/bin/php-cs-fixer fix --config=tools/php-cs-fixer/.php-cs-fixer.dist.php --dry-run --diff --verbose

run_step "QG-008 Docs link integrity" \
  bin/docs-link-check.sh

run_step "QG-008 Docs drift contract" \
  bin/docs-drift-check.sh

run_step "Nginx-only .htaccess guard" \
  bash -lc 'matches="$(rg --files -g ".htaccess" || true)"; if [[ -n "${matches}" ]]; then echo "[FAIL] .htaccess files are not allowed in Nginx-only setup"; echo "${matches}"; exit 1; fi'

run_step "CSS contract check" \
  bin/css-contract-check.sh

run_step "JS contract check" \
  bin/js-contract-check.sh

run_step "QG-009 Codex skills sync" \
  bin/codex-skills-sync.sh --check

echo "[OK] Required QA gates passed (QG-001/002/003/006/008/009)."
