<?php
/**
 * Table of contents SEO strategy.
 *
 * @package SmartyPress_AI_Engine
 * @since 1.0.0
 */

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

/**
 * Inserts a compact table of contents before the first heading.
 */
class SmartyPress_AI_SEO_Strategy_TOC extends SmartyPress_AI_SEO_Strategy_Base {

	public function get_test_id() {
		return 'contentHasTOC';
	}

	public function get_reason() {
		return 'toc';
	}

	public function get_label() {
		return __( 'Add table of contents', 'smartypress-ai-engine' );
	}

	public function get_context_scope() {
		return 'local';
	}

	public function get_strategy_rules() {
		return array_merge(
			parent::get_strategy_rules(),
			array(
				'Return insert_before with reason "toc" and testId "contentHasTOC".',
				'Use the first suitable heading blockClientId as the insertion target.',
				'Do not generate final TOC HTML; return a small placeholder div only. The active SEO provider or frontend adapter will render the native Table of Contents block when available.',
			)
		);
	}

	public function is_applicable( $context, $analysis ) {
		if ( ! empty( $analysis['content_map']['toc_available'] ) ) {
			return false;
		}

		$selected = $this->select_context( $context, $analysis );

		return ! empty( $selected['target_block_id'] ) && ! empty( $selected['headings'] );
	}

	public function select_context( $context, $analysis ) {
		$headings = array();
		foreach ( $this->get_blocks( $context ) as $block ) {
			if ( 'core/heading' === ( $block['name'] ?? '' ) && ! empty( $block['text'] ) ) {
				$headings[] = array(
					'clientId' => $block['clientId'] ?? '',
					'level'    => absint( $block['level'] ?? 2 ),
					'text'     => sanitize_text_field( $block['text'] ),
				);
			}
		}

		return array(
			'testId'          => $this->get_test_id(),
			'reason'          => $this->get_reason(),
			'label'           => $this->get_label(),
			'context_scope'   => $this->get_context_scope(),
			'target_block_id' => $analysis['content_map']['toc_target_block_id'] ?? $analysis['content_map']['first_heading_block_id'] ?? ( $headings[0]['clientId'] ?? '' ),
			'headings'        => $headings,
			'toc_available'   => ! empty( $analysis['content_map']['toc_available'] ),
			'toc_reason'      => sanitize_text_field( $analysis['content_map']['toc_reason'] ?? '' ),
		);
	}

	public function validate_response( $response, $context, $analysis ) {
		$operations = array();
		$warnings   = array_values( array_filter( array_map( 'sanitize_text_field', (array) ( $response['warnings'] ?? array() ) ) ) );
		$selected   = $this->select_context( $context, $analysis );

		foreach ( (array) ( $response['content_operations'] ?? array() ) as $operation ) {
			$operation = $this->normalize_operation( $operation );
			if ( 'insert_before' !== $operation['type'] ) {
				continue;
			}

			if ( '' === $operation['blockClientId'] ) {
				$operation['blockClientId'] = sanitize_text_field( $selected['target_block_id'] ?? '' );
			}

			if ( '' === $operation['blockClientId'] ) {
				continue;
			}

			if ( '' === $operation['html'] ) {
				$operation['html'] = '<div class="smartypress-toc-placeholder"></div>';
			}

			$operation['reason']       = $this->get_reason();
			$operation['testId']       = $this->get_test_id();
			$operation['label']        = $this->get_label();
			$operation['plainSummary'] = $operation['plainSummary'] ?: __( 'Table of Contents block', 'smartypress-ai-engine' );
			$operations[] = $operation;
			break;
		}

		return array(
			'status'             => ! empty( $operations ) ? 'success' : 'validation_failure',
			'testId'             => $this->get_test_id(),
			'reason'             => $this->get_reason(),
			'label'              => $this->get_label(),
			'content_operations' => $operations,
			'fixed_tests'        => ! empty( $operations ) ? array( $this->get_test_id() ) : array(),
			'skipped_tests'      => empty( $operations ) ? array( array( 'id' => $this->get_test_id(), 'reason' => $this->get_failure_reason( $warnings, __( 'AI could not safely choose where to insert the table of contents.', 'smartypress-ai-engine' ) ) ) ) : array(),
			'warnings'           => array_values( array_unique( $warnings ) ),
		);
	}
}
