<?php
/**
 * Bulk item context service.
 *
 * @package SmartyPress_AI_Engine
 */

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

/**
 * Builds per-item context for bulk pipelines.
 */
class SmartyPress_AI_Content_Generator_Bulk_Item_Context_Service {

	/**
	 * Post type extension registry.
	 *
	 * @var SmartyPress_AI_Post_Type_Extension_Registry
	 */
	private $extension_registry;

	/**
	 * Constructor.
	 *
	 * @param SmartyPress_AI_Post_Type_Extension_Registry $extension_registry Extension registry.
	 */
	public function __construct( SmartyPress_AI_Post_Type_Extension_Registry $extension_registry ) {
		$this->extension_registry = $extension_registry;
	}

	/**
	 * Build context for one queue item.
	 *
	 * @param string $topic Topic.
	 * @param string $context Shared context.
	 * @param array  $item Queue item.
	 * @param array  $settings Generation settings.
	 * @return string
	 */
	public function build( $topic, $context, array $item, array $settings ) {
		$parts = array();

		if ( ! empty( $context ) ) {
			$parts[] = $context;
		}

		$row_lines = array();
		foreach (
			array(
				'focus_keyword'      => __( 'Focus keyword', 'smartypress-ai-engine' ),
				'category'           => __( 'Category', 'smartypress-ai-engine' ),
				'product_attributes' => __( 'Product attributes', 'smartypress-ai-engine' ),
				'notes'              => __( 'Row notes', 'smartypress-ai-engine' ),
			) as $key => $label
		) {
			if ( ! empty( $item[ $key ] ) ) {
				$row_lines[] = $label . ': ' . sanitize_textarea_field( $item[ $key ] );
			}
		}

		if ( ! empty( $row_lines ) ) {
			$parts[] = __( 'Row-specific context:', 'smartypress-ai-engine' ) . "\n" . implode( "\n", $row_lines );
		}

		$post_type         = sanitize_key( $settings['post_type'] ?? 'post' );
		$extension_context = $this->extension_registry->build_item_context( $post_type, $item, $settings );
		if ( '' !== trim( $extension_context ) ) {
			$parts[] = $extension_context;
		}

		return trim( implode( "\n\n", array_filter( $parts ) ) );
	}
}
