<?php
/**
 * Keyword in subheading SEO strategy.
 *
 * @package SmartyPress_AI_Engine
 * @since 1.0.0
 */

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

/**
 * Updates one existing heading to include the primary keyword.
 */
class SmartyPress_AI_SEO_Strategy_Keyword_Subheading extends SmartyPress_AI_SEO_Strategy_Base {

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

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

	public function get_label() {
		return __( 'Focus keyword in a subheading', 'smartypress-ai-engine' );
	}

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

	public function get_strategy_rules() {
		return array_merge(
			parent::get_strategy_rules(),
			array(
				'Update one existing H2 or H3 only; do not add a new heading if a suitable one exists.',
				'Include primary_keyword exactly as written, with no inflection, declension, spelling changes, or added words inside the phrase.',
				'Keep the heading concise and preserve the original heading intent.',
			)
		);
	}

	public function is_applicable( $context, $analysis ) {
		return '' !== $this->get_primary_keyword( $context, $analysis ) && ! empty( $this->select_context( $context, $analysis )['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(),
			'primary_keyword' => $this->get_primary_keyword( $context, $analysis ),
			'article_summary' => $analysis['content_summary'] ?? '',
			'headings'        => $headings,
		);
	}

	/**
	 * Treat adding the exact keyword to a previously missing heading as meaningful.
	 *
	 * @param array  $context   Cached SEO context.
	 * @param string $client_id Heading block client ID.
	 * @param string $html      Generated heading HTML.
	 * @param string $keyword   Primary keyword.
	 * @return bool
	 */
	private function heading_keyword_addition_is_meaningful( $context, $client_id, $html, $keyword ) {
		$block = $this->find_block( $this->get_blocks( $context ), $client_id );

		return $block
			&& ! $this->includes_keyword( $block['text'] ?? '', $keyword )
			&& $this->includes_keyword( $html, $keyword );
	}

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

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

			if ( ! $this->includes_keyword( $operation['html'], $keyword ) ) {
				$warnings[] = __( 'The generated heading does not include the exact focus keyword.', 'smartypress-ai-engine' );
				continue;
			}

			$has_meaningful_change = $this->has_meaningful_change( $context, $operation['blockClientId'], $operation['html'] )
				|| $this->heading_keyword_addition_is_meaningful( $context, $operation['blockClientId'], $operation['html'], $keyword );

			if ( ! $has_meaningful_change || $this->has_adjacent_word_duplication( $operation['html'] ) ) {
				$warnings[] = __( 'The generated heading fix was rejected because it did not make a meaningful clean edit.', 'smartypress-ai-engine' );
				continue;
			}

			$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 add the exact focus keyword to a subheading.', 'smartypress-ai-engine' ) ) ) ) : array(),
			'warnings'           => array_values( array_unique( $warnings ) ),
		);
	}
}
