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

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

/**
 * Adds the exact primary keyword near the beginning of the content.
 */
class SmartyPress_AI_SEO_Strategy_Keyword_Intro extends SmartyPress_AI_SEO_Strategy_Base {

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

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

	public function get_label() {
		return __( 'Focus keyword near the beginning', 'smartypress-ai-engine' );
	}

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

	public function get_strategy_rules() {
		return array_merge(
			parent::get_strategy_rules(),
			array(
				'Update the first suitable paragraph only.',
				'Include primary_keyword exactly as written, with no inflection, declension, spelling changes, or added words inside the phrase.',
				'Keep the paragraph natural by restructuring the sentence around the exact keyword phrase.',
			)
		);
	}

	public function is_applicable( $context, $analysis ) {
		return '' !== $this->get_primary_keyword( $context, $analysis ) && ! empty( $this->select_context( $context, $analysis )['target_block']['clientId'] );
	}

	public function select_context( $context, $analysis ) {
		$blocks    = $this->get_blocks( $context );
		$block_id  = $analysis['content_map']['intro_block_id'] ?? '';
		$target    = $block_id ? $this->find_block( $blocks, $block_id ) : null;

		if ( ! $target ) {
			foreach ( $blocks as $block ) {
				if ( ! empty( $block['text'] ) && ( empty( $block['name'] ) || 'core/paragraph' === $block['name'] ) ) {
					$target = $block;
					break;
				}
			}
		}

		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'] ?? '',
			'avoid_repeating' => $analysis['keyword_usage']['avoid_repeating'] ?? array(),
			'target_block'    => $target ? $target : array(),
		);
	}

	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 introduction does not include the exact focus keyword.', 'smartypress-ai-engine' );
				continue;
			}

			if ( ! $this->has_meaningful_change( $context, $operation['blockClientId'], $operation['html'] ) || $this->has_adjacent_word_duplication( $operation['html'] ) ) {
				$warnings[] = __( 'The generated introduction 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 near the beginning of the content.', 'smartypress-ai-engine' ) ) ) ) : array(),
			'warnings'           => array_values( array_unique( $warnings ) ),
		);
	}
}
