<?php

namespace AIPT\Api\BulkGenerator\ImageAlt\Core;

use WC_Product;

class PromptFactory {

	public function getPrompts( array $options, array $product_data, string $additional_prompt = '' ): array {
		$max_length          = isset( $options['maxLength'] ) ? absint( $options['maxLength'] ) : 125;
		$max_length          = $max_length > 0 ? max( 50, min( 250, $max_length ) ) : 125;
		$tone                = isset( $options['tone'] ) ? sanitize_text_field( $options['tone'] ) : 'descriptive';
		$product_name        = sanitize_text_field( $product_data['name'] ?? '' );
		$categories          = sanitize_text_field( $product_data['categories'] ?? '' );
		$description         = \wp_strip_all_tags( $product_data['description'] ?? '' );
		$description         = $this->truncate( $description, 400 );
		$additional_prompt   = \wp_strip_all_tags( $additional_prompt );
		$additional_prompt   = sanitize_textarea_field( $additional_prompt );
		$additional_prompt   = $this->truncate( $additional_prompt, 2000 );
		$additional_section  = '';

		if ( '' !== trim( $additional_prompt ) ) {
			$additional_section = "\n\n<additional_instructions>\n{additional_prompt}\n</additional_instructions>";
		}

		$system_prompt = "# Identity\nYou are an SEO-expert alt text specialist.\n\n# Rules\n1. Maximum {max_length} characters (default 125)\n2. Describe what is visible in the image\n3. Include product name and key features\n4. Natural language (NO keyword stuffing)\n5. Avoid generic phrases like \"image of\" or \"photo of\"\n6. Output plain text only — no quotes, no markdown\n\n# Quality Gate\n- Under {max_length} chars? ✓\n- Describes image content? ✓\n- Includes product context? ✓\n\n<output_format>Plain text only. No quotes or formatting.</output_format>";

		$system_prompt = str_replace( '{max_length}', (string) $max_length, $system_prompt );

		$user_prompt = "<product_data>\nProduct: {product_name}\nCategory: {categories}\nDescription: {description}\n</product_data>{additional_section}\n\n<rules>\n- Write concise, descriptive alt text for this product image.\n- Use a {tone} tone.\n- Stay under {max_length} characters.\n- Output only the alt text.\n</rules>";

		$user_prompt = str_replace(
			[ '{product_name}', '{categories}', '{description}', '{additional_section}', '{additional_prompt}', '{tone}', '{max_length}' ],
			[ $product_name, $categories, $description, $additional_section, $additional_prompt, $tone, (string) $max_length ],
			$user_prompt
		);

		return [
			'system_prompt' => $system_prompt,
			'user_prompt'   => $user_prompt,
		];
	}

	public function enrichWithAttributes( WC_Product $product, string $base_prompt ): string {
		$attributes = $this->collectProductAttributes( $product );

		if ( empty( $attributes ) ) {
			return $base_prompt;
		}

		$lines = [ '<product_attributes>' ];
		foreach ( $attributes as $label => $value ) {
			$lines[] = sprintf(
				'%s: %s',
				\sanitize_text_field( $label ),
				\sanitize_text_field( $value )
			);
		}
		$lines[] = '</product_attributes>';

		$attribute_block = implode( "\n", $lines );

		if ( false !== strpos( $base_prompt, '</product_data>' ) ) {
			return str_replace( '</product_data>', "</product_data>\n\n" . $attribute_block, $base_prompt );
		}

		return $base_prompt . "\n\n" . $attribute_block;
	}

	private function collectProductAttributes( WC_Product $product ): array {
		$attributes = [];

		$product_attributes = (array) $product->get_attributes();

		foreach ( array_keys( $product_attributes ) as $attribute_key ) {
			$value = trim( \wp_strip_all_tags( (string) $product->get_attribute( $attribute_key ) ) );
			if ( '' === $value ) {
				continue;
			}

			$label = \wc_attribute_label( $attribute_key, $product );
			$label = trim( \wp_strip_all_tags( (string) $label ) );

			if ( '' === $label ) {
				$label = ucwords( str_replace( [ 'pa_', '-', '_' ], [ '', ' ', ' ' ], (string) $attribute_key ) );
			}

			$attributes[ $label ] = $value;
		}

		$known_attributes = [
			'pa_color'    => 'Color',
			'color'       => 'Color',
			'pa_size'     => 'Size',
			'size'        => 'Size',
			'pa_material' => 'Material',
			'material'    => 'Material',
			'pa_brand'    => 'Brand',
			'brand'       => 'Brand',
		];

		foreach ( $known_attributes as $attribute_key => $label ) {
			$value = trim( \wp_strip_all_tags( (string) $product->get_attribute( $attribute_key ) ) );
			if ( '' !== $value && ! isset( $attributes[ $label ] ) ) {
				$attributes[ $label ] = $value;
			}
		}

		$weight = trim( (string) $product->get_weight() );
		if ( '' !== $weight ) {
			$attributes['Weight'] = $weight;
		}

		$product_dimensions = (array) $product->get_dimensions( false );
		$raw_dimensions     = array_filter( array_map( 'trim', $product_dimensions ) );
		$dimensions         = empty( $raw_dimensions ) ? '' : implode( ' x ', $raw_dimensions );
		if ( '' !== $dimensions ) {
			$attributes['Dimensions'] = $dimensions;
		}

		return $attributes;
	}

	private function truncate( string $value, int $length ): string {
		if ( function_exists( 'mb_substr' ) ) {
			return mb_substr( $value, 0, $length );
		}

		return substr( $value, 0, $length );
	}
}
