#!/bin/bash
# Runs the same four checks GitLab CI runs on this module (phpcs, phpstan,
# cspell, phpunit) before code leaves for git.drupal.org. Mirrors
# CLAUDE.md item 10/12's documented pre-push checklist.
#
# Enable once per clone:
#   git config core.hooksPath .githooks
#
# Skip for one push (use sparingly):
#   git push --no-verify

set -o pipefail

cd "$(git rev-parse --show-toplevel)" || exit 1

if ! command -v ddev >/dev/null 2>&1; then
  echo "pre-push: ddev not found on PATH, skipping local CI checks." >&2
  exit 0
fi

# This repo is bind-mounted into a separate DDEV site, so run ddev there.
# Override with AI_GOVERNANCE_DDEV_SITE=/path/to/site.
site="${AI_GOVERNANCE_DDEV_SITE:-}"
if [ -z "$site" ]; then
  for dir in . ../ai_governance-dev-site "$HOME/ai_governance-dev-site"; do
    if [ -d "$dir/.ddev" ]; then
      site="$dir"
      break
    fi
  done
fi
if [ -z "$site" ]; then
  echo "pre-push: no DDEV site found; set AI_GOVERNANCE_DDEV_SITE. Skipping local CI checks." >&2
  exit 0
fi
ddev() {
  (cd "$site" && command ddev "$@")
}

status=0

# GitLab CI itself runs phpcs/phpstan/cspell under allow_failure: true
# (see .gitlab-ci.yml) — but that's CI's own leniency, not a reason for
# this local hook to match it. All four checks block the push here.
#
# phpstan-module's scan is scoped to web/modules/custom/ai_governance,
# which includes the ai_governance_midgard submodule's own source — so
# it DOES surface the drupal/midgard vs. mcp_server ^2.0@beta composer
# conflict: midgard_heimdall's classes aren't installable in CI or here,
# so phpstan can't resolve them. phpstan.neon's ignoreErrors rule
# (scoped to identifier: class.notFound + that namespace/path) is what
# actually keeps this check green, not the scan scope.
run_blocking() {
  local label="$1"
  shift
  echo "== $label (blocking) =="
  if ! "$@"; then
    echo "== $label FAILED =="
    status=1
  fi
}

run_blocking "phpcs"    ddev phpcs-module
run_blocking "phpstan"  ddev phpstan-module
run_blocking "cspell"   ddev cspell-module
run_blocking "phpunit"  ddev phpunit-module

if [ "$status" -ne 0 ]; then
  echo
  echo "pre-push: one or more checks failed. Push aborted."
  echo "pre-push: fix the failure above, or 'git push --no-verify' to bypass."
fi

exit $status
