#!/usr/bin/env bash
# adapters/wordpress/hooks/pre-commit — WordPress adapter overlay
#
# Appended below the core pre-commit by `phaseops init` when the
# WordPress adapter is enabled. Preserves the upstream PHP / security
# guardrails that cannot be expressed in the ecosystem-agnostic core.
#
# Sources (generalized for PhaseOps path conventions):
#   - AGENTS.md presence per site root containing app/public/
#   - Unparameterized $wpdb->query() scan on staged PHP files (D150)
#   - strict_types=1 warning on plugin PHP files
#   - PHPStan staged-file check (vendor/bin/phpstan)

set -euo pipefail

if [ "${PHASEOPS_WP_NO_PRECOMMIT:-0}" = "1" ]; then
  exit 0
fi

echo "[wordpress] running WP adapter pre-commit checks..." >&2

MODIFIED_FILES=$(git diff --cached --name-only)
PHP_FILES=$(git diff --cached --name-only --diff-filter=d | grep '\.php$' || true)

for file in $MODIFIED_FILES; do

  # AGENTS.md presence when modifying a site
  if [[ $file == *"app/public/"* ]]; then
    SITE_DIR="${file%%/app/public/*}"
    [ -z "$SITE_DIR" ] && SITE_DIR="."
    if [ ! -f "$SITE_DIR/app/public/AGENTS.md" ]; then
      echo "ERROR [wordpress]: missing AGENTS.md in $SITE_DIR/app/public/" >&2
      exit 1
    fi
  fi

  # Unparameterized SQL on PHP sources only (D150 scope)
  if [[ $file == *.php ]] && [ -f "$file" ]; then
    HAS_QUERY=$(awk 'prev !~ /phpcs:ignore/ && /->[q]uery\(/ {print} {prev=$0}' "$file")
    HAS_PREPARE=$(awk '/->[p]repare\(/' "$file")
    if [ -n "$HAS_QUERY" ] && [ -z "$HAS_PREPARE" ]; then
      echo "ERROR [wordpress]: unparameterized \$wpdb->query() in $file" >&2
      exit 1
    fi
  fi

  # strict_types warning on plugin PHP files
  if [[ $file == *.php ]] && [[ $file == *"wp-content/plugins/"* ]]; then
    if ! grep -q "declare(strict_types=1);" "$file" 2>/dev/null; then
      echo "WARN [wordpress]: missing strict_types=1 in $file" >&2
    fi
  fi

done

# PHPStan staged-file check
if [ -f "vendor/bin/phpstan" ] && [ -n "$PHP_FILES" ]; then
  echo "[wordpress] PHPStan on staged files..." >&2
  vendor/bin/phpstan analyze --no-progress $PHP_FILES || {
    echo "ERROR [wordpress]: PHPStan failed on staged files." >&2
    exit 1
  }
fi
