<?php
/**
 * SEO Analysis content plan hooks.
 *
 * @package SmartyPress_AI_Engine
 */

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

/**
 * Integrates SEO analysis with content plan generation.
 */
class SmartyPress_AI_SEO_Analysis_Plan_Hooks {

	/**
	 * Register hooks.
	 *
	 * @return void
	 */
	public function register_hooks() {
		add_filter( 'smartypress_ai_content_plan_seo_analysis_enabled', array( $this, 'is_content_plan_seo_analysis_enabled' ), 10, 4 );
		add_filter( 'smartypress_ai_content_plan_prompt', array( $this, 'append_content_plan_research_prompt' ), 10, 2 );
		add_filter( 'smartypress_ai_content_plan_request_params', array( $this, 'add_content_plan_request_params' ), 10, 2 );
		add_action( 'smartypress_ai_content_plan_research_generated', array( $this, 'log_content_plan_research' ), 10, 2 );
	}

	/**
	 * Determine if plan generation should use SEO analysis.
	 *
	 * @param bool   $enabled       Current state.
	 * @param string $provider_name Provider name.
	 * @param string $model         Model ID.
	 * @param array  $context       Plan generation context.
	 * @return bool
	 */
	public function is_content_plan_seo_analysis_enabled( $enabled, $provider_name, $model, $context ) {
		if ( ! empty( $enabled ) || empty( $model ) ) {
			return (bool) $enabled;
		}

		return SmartyPress_AI_Model_Map::supports( $provider_name, $model, 'web_search' );
	}

	/**
	 * Append competitor research instructions to the plan prompt.
	 *
	 * @param string $prompt  Current prompt.
	 * @param array  $context Plan generation context.
	 * @return string
	 */
	public function append_content_plan_research_prompt( $prompt, $context ) {
		if ( empty( $context['seo_analysis_enabled'] ) ) {
			return $prompt;
		}

		$topic = sanitize_text_field( $context['topic'] ?? '' );
		$context_text = sanitize_textarea_field( $context['context'] ?? '' );
		$language = sanitize_text_field( $context['language'] ?? '' );

		$prompt .= "\n\n" . __( 'Competitor research instructions: before creating the plan, extract 3-8 search queries from the user topic and context. Use SEO analysis to identify competing articles or pages for the main search intent. Analyze competitor titles, recurring headings, keyword clusters, content angles, missing angles, and opportunities. Do not copy competitors. Use the research to create a stronger original editorial plan.', 'smartypress-ai-engine' );
		$prompt .= "\n" . __( 'Return competitor research only inside an optional research object in the JSON. The research object may contain enabled, searchQueries, competitors, keywordGaps, titlePatterns, and contentOpportunities.', 'smartypress-ai-engine' );
		$prompt .= "\n" . __( 'Each research competitor may contain title, url, observedKeywords, headingPatterns, and contentAngle. Keep competitor data concise and factual.', 'smartypress-ai-engine' );
		$prompt .= "\n\n" . sprintf(
			/* translators: 1: topic, 2: context, 3: language. */
			__( 'Research target: topic "%1$s"; context "%2$s"; language "%3$s". Prefer competitors and queries relevant to this language and search intent.', 'smartypress-ai-engine' ),
			$topic,
			$context_text,
			$language
		);

		return $prompt;
	}

	/**
	 * Add provider web search request flags to content plan generation params.
	 *
	 * @param array $params  Request params.
	 * @param array $context Plan generation context.
	 * @return array
	 */
	public function add_content_plan_request_params( $params, $context ) {
		$params['web_search'] = ! empty( $context['seo_analysis_enabled'] );

		return $params;
	}

	/**
	 * Log successful research generation without storing model output.
	 *
	 * @param array $plan    Normalized plan.
	 * @param array $context Plan generation context.
	 * @return void
	 */
	public function log_content_plan_research( $plan, $context ) {
		if ( empty( $context['seo_analysis_enabled'] ) || ! class_exists( 'SmartyPress_AI_Logger' ) ) {
			return;
		}

		$research = is_array( $plan['research'] ?? null ) ? $plan['research'] : array();

		SmartyPress_AI_Logger::log_module_event(
			'content_generator',
			'plan_research_completed',
			array(
				'provider'           => sanitize_key( $context['provider'] ?? '' ),
				'model'              => sanitize_text_field( $context['model'] ?? '' ),
				'seo_analysis_enabled' => true,
				'search_query_count' => count( $research['searchQueries'] ?? array() ),
				'competitor_count'   => count( $research['competitors'] ?? array() ),
				'has_keyword_gaps'   => ! empty( $research['keywordGaps'] ),
			),
			true
		);
	}
}
