<?php
/**
 * SEO fix pipeline runner.
 *
 * @package SmartyPress_AI_Engine
 * @since 1.0.0
 */

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

/**
 * Orchestrates analysis, metadata generation, content strategies, and merging.
 */
class SmartyPress_AI_SEO_Fix_Pipeline_Runner {

	/**
	 * Analysis service.
	 *
	 * @var SmartyPress_AI_SEO_Analysis_Service
	 */
	private $analysis_service;

	/**
	 * Metadata step service.
	 *
	 * @var SmartyPress_AI_SEO_Meta_Step_Service
	 */
	private $meta_step_service;

	/**
	 * Content strategy runner.
	 *
	 * @var SmartyPress_AI_SEO_Content_Strategy_Runner
	 */
	private $content_strategy_runner;

	/**
	 * Result normalizer.
	 *
	 * @var SmartyPress_AI_SEO_Result_Normalizer
	 */
	private $result_normalizer;

	/**
	 * Constructor.
	 *
	 * @param SmartyPress_AI_SEO_Analysis_Service         $analysis_service        Analysis service.
	 * @param SmartyPress_AI_SEO_Meta_Step_Service        $meta_step_service       Meta step service.
	 * @param SmartyPress_AI_SEO_Content_Strategy_Runner  $content_strategy_runner Content strategy runner.
	 * @param SmartyPress_AI_SEO_Result_Normalizer        $result_normalizer       Result normalizer.
	 */
	public function __construct( $analysis_service, $meta_step_service, $content_strategy_runner, $result_normalizer ) {
		$this->analysis_service        = $analysis_service;
		$this->meta_step_service       = $meta_step_service;
		$this->content_strategy_runner = $content_strategy_runner;
		$this->result_normalizer       = $result_normalizer;
	}

	/**
	 * Run the SEO fix pipeline for a cached context.
	 *
	 * @param string $context_id  Context ID.
	 * @param array  $context     Cached context.
	 * @param object $provider    AI provider.
	 * @param string $language    Language.
	 * @param string $model       Model.
	 * @param float  $temperature Temperature.
	 * @return array|WP_Error
	 */
	public function run( $context_id, $context, $provider, $language, $model, $temperature ) {
		$analysis = $this->analysis_service->get_or_create_analysis( $context_id, $context, $provider, $language, $model, $temperature );

		if ( is_wp_error( $analysis ) ) {
			return $analysis;
		}

		$meta_result    = $this->meta_step_service->run( $context, $analysis, $provider, $language, $model, $temperature );
		$content_result = $this->content_strategy_runner->run( $context, $analysis, $provider, $language, $model, $temperature );

		return $this->result_normalizer->merge_pipeline_results( $context, $analysis, $meta_result, $content_result );
	}
}
