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

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

/**
 * Adds the exact primary keyword to one suitable paragraph.
 */
class SmartyPress_AI_SEO_Strategy_Keyword_Content extends SmartyPress_AI_SEO_Strategy_Base {

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

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

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

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

	public function get_strategy_rules() {
		return array_merge(
			parent::get_strategy_rules(),
			array(
				'Replace one existing paragraph only.',
				'Insert primary_keyword exactly once and exactly as written, with no inflection, declension, spelling changes, or added words inside the phrase.',
				'Preserve the paragraph meaning and avoid keyword stuffing.',
			)
		);
	}

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

	public function select_context( $context, $analysis ) {
		$blocks     = $this->get_blocks( $context );
		$candidates = array();

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

			$candidates[] = $block;
			if ( count( $candidates ) >= 4 ) {
				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'] ?? '',
			'keyword_usage'    => $analysis['keyword_usage'] ?? array(),
			'candidate_blocks' => $candidates,
		);
	}

	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 content fix 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 content fix was rejected because it did not make a meaningful clean edit.', 'smartypress-ai-engine' );
				continue;
			}

			$operation['reason']       = $this->get_reason();
			$operation['testId']       = $this->get_test_id();
			$operation['label']        = $this->get_label();
			$operation['plainSummary'] = $operation['plainSummary'] ?: __( 'Adds the exact focus keyword to the content.', '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 add the exact focus keyword to the content.', 'smartypress-ai-engine' ) ) ) ) : array(),
			'warnings'           => array_values( array_unique( $warnings ) ),
		);
	}
}
