#!/usr/bin/env bash
# Verify plugin header consistency and PHP syntax.
# Usage: tools/test-plugin.sh bw-<slug>

source "$(dirname "$0")/lib/common.sh"

SLUG="${1:-}"
require_slug "$SLUG"

PLUGIN_DIR="${BW_PLUGINS_DIR}/${SLUG}"
MAIN="${PLUGIN_DIR}/${SLUG}.php"
ERRORS=0

log_info "Testing ${SLUG}..."

# 1. PHP syntax check on every .php file (via docker — no host PHP).
PHP_LINT_IMAGE="php:8.1-cli"
PHP_LINT_SCRIPT='for f in "$@"; do php -l "$f" >/dev/null 2>&1 || { echo "SYNTAX_ERROR:$f"; php -l "$f" 2>&1 | head -3; }; done'
while IFS= read -r -d '' f; do
	rel="${f#${PLUGIN_DIR}/}"
	if ! out=$(docker run --rm -v "${PLUGIN_DIR}:/p" "$PHP_LINT_IMAGE" php -l "/p/${rel}" 2>&1); then
		log_error "Syntax error in $rel: $out"
		ERRORS=$((ERRORS + 1))
	fi
done < <(find "$PLUGIN_DIR" -name '*.php' -not -path '*/vendor/*' -print0)

# 2. Required header fields.
for field in "Plugin Name" "Version" "Requires at least" "Requires PHP" "Author" "License" "Text Domain" "Update URI"; do
	val=$(plugin_header_field "$SLUG" "$field" || true)
	if [[ -z "$val" ]]; then
		log_error "Missing header field: ${field}"
		ERRORS=$((ERRORS + 1))
	fi
done

# 3. Update URI must point to plugins.bowden.works/<slug>/
update_uri=$(plugin_header_field "$SLUG" "Update URI" || true)
expected_uri="https://plugins.bowden.works/${SLUG}/"
if [[ "$update_uri" != "$expected_uri" ]]; then
	log_error "Update URI is '${update_uri}', expected '${expected_uri}'"
	ERRORS=$((ERRORS + 1))
fi

# 4. Version consistency: header version vs VERSION constant vs CHANGELOG.
HDR_VER=$(plugin_header_version "$SLUG")
if [[ -z "$HDR_VER" ]]; then
	log_error "Cannot parse version from plugin header"
	ERRORS=$((ERRORS + 1))
fi

SLUG_UU=$(slug_to_upper_underscore "$SLUG")
CONST_VER=$(grep -m1 -E "define\(\s*'${SLUG_UU}_VERSION'" "$MAIN" | sed -E "s/.*'([^']+)'\s*\).*/\1/" || true)
if [[ -n "$CONST_VER" && "$CONST_VER" != "$HDR_VER" ]]; then
	log_error "VERSION constant (${CONST_VER}) does not match plugin header (${HDR_VER})"
	ERRORS=$((ERRORS + 1))
fi

if [[ -f "${PLUGIN_DIR}/CHANGELOG.md" ]]; then
	if ! grep -qE "^## \[${HDR_VER}\]" "${PLUGIN_DIR}/CHANGELOG.md"; then
		log_warn "CHANGELOG.md has no entry for version ${HDR_VER} (required before release)"
	fi
else
	log_error "CHANGELOG.md missing"
	ERRORS=$((ERRORS + 1))
fi

# 5. Required docs.
for f in README.md CLAUDE.md CHANGELOG.md LICENSE docs/ARCHITECTURE.md docs/SPEC.md docs/TESTING.md; do
	if [[ ! -f "${PLUGIN_DIR}/${f}" ]]; then
		log_error "Missing required file: ${f}"
		ERRORS=$((ERRORS + 1))
	fi
done

# 6. ABSPATH guard on all PHP files (except vendor).
while IFS= read -r -d '' f; do
	if ! head -20 "$f" | grep -q "ABSPATH"; then
		log_warn "Missing ABSPATH guard: $(realpath --relative-to="$PLUGIN_DIR" "$f")"
	fi
done < <(find "$PLUGIN_DIR" -name '*.php' -not -path '*/vendor/*' -not -name 'uninstall.php' -print0)

if (( ERRORS > 0 )); then
	log_error "${ERRORS} error(s) found"
	exit 1
fi

log_ok "test-plugin: ${SLUG} passed (version ${HDR_VER})"
