<?php
/**
 * Competitor research service.
 *
 * @package SmartyPress_AI_Engine
 */

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

/**
 * Runs the staged competitor research pipeline.
 */
class SmartyPress_AI_SEO_Analysis_Competitor_Research_Service {

	/**
	 * Prompt builder.
	 *
	 * @var SmartyPress_AI_SEO_Analysis_Prompts
	 */
	private $prompts;

	/**
	 * Response parser.
	 *
	 * @var SmartyPress_AI_SEO_Analysis_Response_Parser
	 */
	private $parser;

	/**
	 * Constructor.
	 *
	 * @param SmartyPress_AI_SEO_Analysis_Prompts         $prompts Prompt builder.
	 * @param SmartyPress_AI_SEO_Analysis_Response_Parser $parser  Response parser.
	 */
	public function __construct( SmartyPress_AI_SEO_Analysis_Prompts $prompts, SmartyPress_AI_SEO_Analysis_Response_Parser $parser ) {
		$this->prompts = $prompts;
		$this->parser  = $parser;
	}

	/**
	 * Run URL discovery and page analysis.
	 *
	 * @param SmartyPress_AI_AI_Provider $provider       Provider instance.
	 * @param string                     $model          Model ID.
	 * @param string                     $keyword        Focus keyword.
	 * @param string                     $language       Target language.
	 * @param int                        $limit          Competitor limit.
	 * @param int                        $analysis_limit Number of pages to analyze.
	 * @return array
	 */
	public function research( $provider, $model, $keyword, $language, $limit, $analysis_limit ) {
		if ( class_exists( 'SmartyPress_AI_Token_Tracker' ) ) {
			SmartyPress_AI_Token_Tracker::set_module( 'seo-analysis' );
		}

		$url_result = $this->search_competitor_urls( $provider, $model, $keyword, $language, $limit );
		if ( empty( $url_result['success'] ) ) {
			return $url_result;
		}

		$competitors = $this->analyze_competitor_pages( $provider, $model, $keyword, $language, $url_result['competitors'], $analysis_limit );

		if ( empty( $competitors ) ) {
			return array(
				'success'    => false,
				'error'      => __( 'No suitable competitor pages were found for this query.', 'smartypress-ai-engine' ),
				'error_code' => 'empty_results',
			);
		}

		return array(
			'success'     => true,
			'competitors' => $competitors,
		);
	}

	/**
	 * Find organic competitor URLs without page-level extraction.
	 *
	 * @param SmartyPress_AI_AI_Provider $provider Provider instance.
	 * @param string                     $model    Model ID.
	 * @param string                     $keyword  Focus keyword.
	 * @param string                     $language Target language.
	 * @param int                        $limit    Competitor limit.
	 * @return array
	 */
	private function search_competitor_urls( $provider, $model, $keyword, $language, $limit ) {
		$result = $provider->generate_content(
			$this->prompts->build_competitor_url_search_prompt( $keyword, $language, $limit ),
			array(
				'model'           => $model,
				'system_prompt'   => $this->prompts->build_competitor_search_system_prompt( $language ),
				'temperature'     => 0.1,
				'max_tokens'      => 2500,
				'request_timeout' => 90,
				'web_search'      => true,
			)
		);

		if ( empty( $result['success'] ) ) {
			return $result;
		}

		$competitors = $this->parser->parse_competitor_url_response( $result['content'] ?? '', $limit );
		if ( empty( $competitors ) ) {
			return array(
				'success'    => false,
				'error'      => __( 'No suitable competitor pages were found for this query.', 'smartypress-ai-engine' ),
				'error_code' => 'empty_results',
			);
		}

		return array(
			'success'     => true,
			'competitors' => $competitors,
		);
	}

	/**
	 * Analyze each found competitor page independently.
	 *
	 * @param SmartyPress_AI_AI_Provider $provider       Provider instance.
	 * @param string                     $model          Model ID.
	 * @param string                     $keyword        Focus keyword.
	 * @param string                     $language       Target language.
	 * @param array                      $competitors    URL search results.
	 * @param int                        $analysis_limit Number of pages to analyze.
	 * @return array
	 */
	private function analyze_competitor_pages( $provider, $model, $keyword, $language, array $competitors, $analysis_limit ) {
		$analyzed = array();

		foreach ( $competitors as $index => $competitor ) {
			if ( $index >= $analysis_limit ) {
				$competitor['analysisStatus'] = 'found';
				$analyzed[] = $competitor;
				continue;
			}

			$analysis = $this->analyze_competitor_page( $provider, $model, $keyword, $language, $competitor );
			$analyzed[] = array_merge( $competitor, $analysis );
		}

		return $analyzed;
	}

	/**
	 * Analyze one competitor URL for actual headings and SEO data.
	 *
	 * @param SmartyPress_AI_AI_Provider $provider   Provider instance.
	 * @param string                     $model      Model ID.
	 * @param string                     $keyword    Focus keyword.
	 * @param string                     $language   Target language.
	 * @param array                      $competitor Competitor URL metadata.
	 * @return array
	 */
	private function analyze_competitor_page( $provider, $model, $keyword, $language, array $competitor ) {
		$result = $provider->generate_content(
			$this->prompts->build_competitor_page_analysis_prompt( $keyword, $language, $competitor ),
			array(
				'model'           => $model,
				'system_prompt'   => $this->prompts->build_competitor_search_system_prompt( $language ),
				'temperature'     => 0.1,
				'max_tokens'      => 3500,
				'request_timeout' => 180,
				'web_search'      => true,
			)
		);

		if ( empty( $result['success'] ) ) {
			return array(
				'analysisStatus' => 'failed',
				'analysisError'  => sanitize_text_field( $result['error'] ?? __( 'Failed to analyze competitor page.', 'smartypress-ai-engine' ) ),
			);
		}

		$analysis = $this->parser->parse_competitor_page_analysis_response( $result['content'] ?? '' );
		if ( empty( $analysis['headings'] ) && empty( $analysis['keywords'] ) ) {
			$analysis['analysisStatus'] = 'partial';
			$analysis['analysisError'] = $analysis['analysisError'] ?: __( 'Page analysis returned no headings or keywords.', 'smartypress-ai-engine' );
		}

		return $analysis;
	}
}
