<?php
namespace WPLens\Schema\Generators;

if ( ! defined( 'ABSPATH' ) ) { exit; }

final class FaqGenerator implements \WPLens\Schema\Generator {

	public function get_slug(): string  { return 'faq'; }
	public function get_label(): string { return __( 'FAQPage (auto-detected from Q & A headings)', 'lens-ai-visibility-monitor' ); }

	public function applies( ?\WP_Post $post = null ): bool {
		if ( ! $post instanceof \WP_Post ) { return false; }
		return in_array( $post->post_type, array( 'post', 'page' ), true );
	}

	public function generate( ?\WP_Post $post = null ): ?array {
		if ( ! $post ) { return null; }

		$pairs = $this->extract_qa_pairs( (string) $post->post_content );
		if ( count( $pairs ) < 2 ) {
			// Not enough Q&A pattern to warrant FAQPage schema.
			return null;
		}

		$entities = array();
		foreach ( $pairs as $p ) {
			$entities[] = array(
				'@type'          => 'Question',
				'name'           => $p['q'],
				'acceptedAnswer' => array(
					'@type' => 'Answer',
					'text'  => $p['a'],
				),
			);
		}

		return array(
			'@type'      => 'FAQPage',
			'@id'        => get_permalink( $post ) . '#faq',
			'mainEntity' => $entities,
		);
	}

	/**
	 * @return array<int, array{q:string, a:string}>
	 */
	private function extract_qa_pairs( string $content ): array {
		$pairs = array();
		// Match h2|h3 whose inner text ends with a question mark, then capture content up to the next heading or end.
		if ( ! preg_match_all(
			'#<h([23])\b[^>]*>(?P<q>[^<]*\?)\s*</h\1>(?P<a>.*?)(?=<h[23]\b|$)#is',
			$content,
			$m,
			PREG_SET_ORDER
		) ) {
			return $pairs;
		}

		foreach ( $m as $row ) {
			$q = trim( wp_strip_all_tags( $row['q'] ) );
			$a = trim( wp_strip_all_tags( $row['a'] ) );
			if ( '' === $q || '' === $a ) {
				continue;
			}
			// Compress whitespace
			$a = preg_replace( '/\s+/u', ' ', $a );
			$pairs[] = array( 'q' => $q, 'a' => $a );
		}
		return $pairs;
	}
}
