<?php
/**
 * Short paragraphs SEO strategy.
 *
 * @package SmartyPress_AI_Engine
 * @since 1.0.0
 */

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

/**
 * Splits one overly long paragraph into shorter readable paragraphs.
 */
class SmartyPress_AI_SEO_Strategy_Short_Paragraphs extends SmartyPress_AI_SEO_Strategy_Base {

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

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

	public function get_label() {
		return __( 'Shorter paragraphs', 'smartypress-ai-engine' );
	}

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

	public function get_strategy_rules() {
		return array_merge(
			parent::get_strategy_rules(),
			array(
				'Replace only the target paragraph with 2-4 shorter <p> paragraphs.',
				'Preserve all facts, links, entities, and wording as much as possible.',
				'Do not add new SEO claims or unrelated content.',
			)
		);
	}

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

	public function select_context( $context, $analysis ) {
		$target = null;

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

			$text_length = function_exists( 'mb_strlen' ) ? mb_strlen( $block['text'] ) : strlen( $block['text'] );
			if ( $text_length >= 360 ) {
				$target = $block;
				break;
			}

			if ( ! $target ) {
				$target = $block;
			}
		}

		return array(
			'testId'          => $this->get_test_id(),
			'reason'          => $this->get_reason(),
			'label'           => $this->get_label(),
			'context_scope'   => $this->get_context_scope(),
			'article_summary' => $analysis['content_summary'] ?? '',
			'target_block'    => $target ? $target : array(),
			'instruction'     => 'Split only the target paragraph into 2-4 shorter paragraphs. Preserve all facts, links, and wording as much as possible.',
		);
	}

	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 );
		$target_id  = sanitize_text_field( $selected['target_block']['clientId'] ?? '' );

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

			if ( '' !== $target_id && $operation['blockClientId'] !== $target_id ) {
				$warnings[] = __( 'The paragraph split targeted the wrong block.', 'smartypress-ai-engine' );
				continue;
			}

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

			if ( substr_count( strtolower( $operation['html'] ), '<p' ) < 2 ) {
				$warnings[] = __( 'The generated paragraph split did not create multiple paragraphs.', 'smartypress-ai-engine' );
				continue;
			}

			$operation['reason']       = $this->get_reason();
			$operation['testId']       = $this->get_test_id();
			$operation['label']        = $this->get_label();
			$operation['plainSummary'] = $operation['plainSummary'] ?: __( 'Splits a long paragraph into shorter readable paragraphs.', '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 split the paragraph without changing meaning.', 'smartypress-ai-engine' ) ) ) ) : array(),
			'warnings'           => array_values( array_unique( $warnings ) ),
		);
	}
}
