<?php
/**
 * AEO Optimizer integration — defers schema output to AEO's adapter (per
 * ADR-19, mode 1).
 *
 * AEO Optimizer maintains a single active SEO adapter (Yoast, Rank Math,
 * AIOSEO, SEOPress, TSF, or standalone). Each adapter exposes
 * `add_schema_piece(array $piece)` for third-party plugins to queue pieces
 * into the right output channel (Yoast graph filter / standalone wp_head /
 * etc). We just hand it our vehicle/dealer/offer/breadcrumb/FAQ pieces on
 * `wp_head` priority 5 — early enough that the active adapter still has
 * time to add them before its own emit at priority 10–99.
 *
 * Falls back gracefully if AEO isn't loaded (mode detection should prevent
 * us getting here, but the guard is cheap insurance).
 *
 * @package ThemeREX\AutoDealer
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Integrations\AeoOptimizer;

defined( 'ABSPATH' ) || exit;
use ThemeREX\AutoDealer\Integrations\Schema\SchemaGenerator;

class AeoOptimizerIntegration {

	public function register(): void {
		// AEO's adapters emit the graph at `wp_head` priority 1. Queue our
		// pieces on `template_redirect` (which fires *before* wp_head) so
		// they're in the buffer before AEO flushes.
		add_action( 'template_redirect', array( $this, 'queuePieces' ), 20 );
	}

	public function queuePieces(): void {
		$adapter = $this->resolveAdapter();
		if ( null === $adapter || ! method_exists( $adapter, 'add_schema_piece' ) ) {
			return;
		}

		// Source of pieces is `SchemaGenerator::buildGraph()` so anything
		// registered through the `trx_ad_schema_graph_pieces` filter
		// (Phase 18 AEO/GEO modules) flows through automatically. AEO's
		// adapter system handles BreadcrumbList dedup on its own, so we
		// hand it everything including breadcrumbs.
		foreach ( SchemaGenerator::buildGraph() as $piece ) {
			if ( is_array( $piece ) && ! empty( $piece ) ) {
				$adapter->add_schema_piece( $piece );
			}
		}
	}

	/**
	 * Get AEO's active SEO adapter. Defensively probes the public accessors
	 * AEO exposes so a future API rename doesn't break the integration.
	 *
	 * @return object|null AEO_Abstract_SEO_Adapter instance.
	 */
	private function resolveAdapter() {
		if ( function_exists( 'aeo_optimizer' ) ) {
			$plugin = aeo_optimizer();
			if ( is_object( $plugin ) && method_exists( $plugin, 'get_seo_adapter' ) ) {
				return $plugin->get_seo_adapter();
			}
		}
		if ( class_exists( '\AEO_Plugin' ) && method_exists( '\AEO_Plugin', 'instance' ) ) {
			$plugin = \AEO_Plugin::instance();
			if ( is_object( $plugin ) && method_exists( $plugin, 'get_seo_adapter' ) ) {
				return $plugin->get_seo_adapter();
			}
		}
		return null;
	}
}
