#!/usr/bin/env bash
# ERPFlow coding-standard / architecture gate (Phase 1).
# Used by scripts/ci-local.sh and GitHub Actions.
#
# Usage:
#   ./scripts/check-coding-standard.sh
#   ./scripts/check-coding-standard.sh --write-baseline
#   ./scripts/check-coding-standard.sh --no-baseline
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
BACKEND="$ROOT/backend"
LINT="$BACKEND/scripts/architecture-lint.php"

die() { echo "error: $*" >&2; exit 1; }

have() { command -v "$1" >/dev/null 2>&1; }

backend_container_running() {
  docker ps --filter name=erpflow-backend --filter status=running \
    --format '{{.Names}}' 2>/dev/null | grep -qx erpflow-backend
}

run_host() {
  have php || die "php not found on PATH (or use Docker: make up)"
  (cd "$BACKEND" && php "$LINT" "$@")
}

run_docker() {
  have docker || die "docker not found"
  backend_container_running || die "erpflow-backend is not running; start with: make up"
  docker compose --env-file "$BACKEND/.env" exec -T backend \
    php scripts/architecture-lint.php "$@"
}

main() {
  test -f "$LINT" || die "missing $LINT"

  # Prefer Docker when the backend container is up so CI/local match PHP 8.4.
  if have docker && backend_container_running; then
    run_docker "$@"
  elif have php && [[ -f "$BACKEND/vendor/autoload.php" ]]; then
    run_host "$@"
  else
    die "need a running erpflow-backend container (make up), or host PHP+vendor"
  fi
}

main "$@"
