<?php

namespace AIPT\Api\BulkGenerator\ImageAlt;

use AIPT\Api\BulkGenerator\Common\AIClientFactory;
use AIPT\Api\BulkGenerator\Common\ProductDataFormatter;
use AIPT\Api\BulkGenerator\ImageAlt\Core\PromptFactory;
use AIPT\Core\ErrorHandler;

class Service {

	private $prompt_factory;

	public function __construct() {
		$this->prompt_factory = new PromptFactory();
	}

	/**
	 * Legacy v1 generation: derive attachment IDs from product-level options
	 * (includeGallery flag) and delegate to the v2 selections path.
	 */
	public function bulk_generate( array $product_ids, array $options ): array {
		$selections = [];

		foreach ( $product_ids as $product_id ) {
			$product_id = absint( $product_id );
			$product    = wc_get_product( $product_id );

			if ( ! $product ) {
				continue;
			}

			$attachment_ids = $this->collect_image_ids( $product, $options );

			if ( ! empty( $attachment_ids ) ) {
				$selections[] = [
					'productId'     => $product_id,
					'attachmentIds' => $attachment_ids,
				];
			} else {
				$selections[] = [
					'productId'     => $product_id,
					'attachmentIds' => [],
					'_no_images'    => true,
				];
			}
		}

		return $this->bulk_generate_by_selections( $selections, $options );
	}

	public function bulk_generate_by_selections( array $selections, array $options ): array {
		$results                = [];
		$api_provider           = sanitize_text_field( $options['provider'] ?? get_option( 'aipt_api_provider', 'openai' ) );
		$model                  = $options['model'] ?? null;
		$max_length             = isset( $options['maxLength'] ) ? absint( $options['maxLength'] ) : 125;
		$max_length             = $max_length > 0 ? max( 50, min( 250, $max_length ) ) : 125;
		$enrich_with_attributes = ! empty( $options['enrichWithAttributes'] );
		$per_request_prompt     = sanitize_textarea_field( $options['additionalPrompt'] ?? '' );
		$site_level_prompt      = sanitize_textarea_field( get_option( 'aipt_image_alt_additional_prompt', '' ) );

		if ( ! empty( $site_level_prompt ) && ! empty( $per_request_prompt ) ) {
			$additional_prompt = $site_level_prompt . "\n" . $per_request_prompt;
		} elseif ( ! empty( $site_level_prompt ) ) {
			$additional_prompt = $site_level_prompt;
		} else {
			$additional_prompt = $per_request_prompt;
		}

		$client = AIClientFactory::create( $api_provider, [
			'generation_type' => 'image_alt',
			'model'           => $model,
		] );

		foreach ( $selections as $selection ) {
			$product_id     = absint( $selection['productId'] ?? 0 );
			$attachment_ids = array_filter( array_map( 'absint', (array) ( $selection['attachmentIds'] ?? [] ) ) );

			if ( $product_id <= 0 ) {
				continue;
			}

			$product = wc_get_product( $product_id );

			if ( ! $product ) {
				continue;
			}

			if ( empty( $attachment_ids ) ) {
				$results[] = [
					'product_id'    => $product_id,
					'attachment_id' => 0,
					'image_url'     => '',
					'alt_text'      => '',
					'status'        => 'error',
					'error'         => __( 'No images selected for this product.', 'ai-product-tools' ),
				];
				continue;
			}

			$product_data = ProductDataFormatter::getFormattedProductData( $product );

			foreach ( $attachment_ids as $attachment_id ) {
				$image_url = \wp_get_attachment_url( $attachment_id );

				if ( empty( $image_url ) ) {
					$results[] = [
						'product_id'    => $product_id,
						'attachment_id' => $attachment_id,
						'image_url'     => '',
						'alt_text'      => '',
						'status'        => 'error',
						'error'         => __( 'Could not retrieve image URL for attachment.', 'ai-product-tools' ),
					];
					continue;
				}

				try {
					$prompts = $this->prompt_factory->getPrompts(
						$options,
						[
							'name'        => $product_data['name'] ?? $product->get_name(),
							'categories'  => $product_data['categories'] ?? '',
							'description' => \wp_strip_all_tags( $product->get_description() ),
						],
						is_string( $additional_prompt ) ? $additional_prompt : ''
					);

					if ( $enrich_with_attributes ) {
						$prompts['user_prompt'] = $this->prompt_factory->enrichWithAttributes( $product, $prompts['user_prompt'] );
					}

					$alt_text = $client->generate_from_vision(
						$prompts['system_prompt'],
						$prompts['user_prompt'],
						$image_url,
						$model
					);

					$alt_text = \wp_strip_all_tags( trim( $alt_text ) );
					$alt_text = trim( $alt_text, '"\'`' );
					$alt_text = mb_substr( $alt_text, 0, $max_length );

					$results[] = [
						'product_id'    => $product_id,
						'attachment_id' => $attachment_id,
						'image_url'     => \esc_url_raw( $image_url ),
						'alt_text'      => $alt_text,
						'status'        => 'pending',
					];

				} catch ( \Exception $e ) {
					$results[] = [
						'product_id'    => $product_id,
						'attachment_id' => $attachment_id,
						'image_url'     => \esc_url_raw( $image_url ),
						'alt_text'      => '',
						'status'        => 'error',
						'error'         => ErrorHandler::sanitize_error_for_display( $e->getMessage() ),
					];
				}
			}
		}

		return $results;
	}

	public function get_product_images( int $product_id ): array {
		$product = wc_get_product( $product_id );

		if ( ! $product ) {
			return [
				'product_id'   => $product_id,
				'product_name' => '',
				'featured'     => null,
				'gallery'      => [],
			];
		}

		$result = [
			'product_id'   => $product_id,
			'product_name' => $product->get_name(),
			'featured'     => null,
			'gallery'      => [],
		];

		$featured_id = (int) $product->get_image_id();
		if ( $featured_id > 0 ) {
			$result['featured'] = $this->format_attachment( $featured_id, true );
		}

		foreach ( (array) $product->get_gallery_image_ids() as $gallery_id ) {
			$gallery_id = absint( $gallery_id );
			if ( $gallery_id > 0 ) {
				$result['gallery'][] = $this->format_attachment( $gallery_id, false );
			}
		}

		return $result;
	}

	private function format_attachment( int $attachment_id, bool $is_featured ): array {
		$url           = \wp_get_attachment_url( $attachment_id );
		$thumbnail_url = \wp_get_attachment_image_url( $attachment_id, 'thumbnail' );
		$metadata      = \wp_get_attachment_metadata( $attachment_id );
		$attached_file = \get_attached_file( $attachment_id );
		$filename      = $attached_file ? basename( $attached_file ) : '';
		$current_alt   = \get_post_meta( $attachment_id, '_wp_attachment_image_alt', true );

		return [
			'id'            => $attachment_id,
			'url'           => \esc_url_raw( $url ?: '' ),
			'thumbnail_url' => \esc_url_raw( $thumbnail_url ?: $url ?: '' ),
			'filename'      => sanitize_text_field( $filename ),
			'width'         => (int) ( $metadata['width'] ?? 0 ),
			'height'        => (int) ( $metadata['height'] ?? 0 ),
			'is_featured'   => $is_featured,
			'current_alt'   => sanitize_text_field( is_string( $current_alt ) ? $current_alt : '' ),
		];
	}

	private function collect_image_ids( \WC_Product $product, array $options ): array {
		$ids         = [];
		$featured_id = (int) $product->get_image_id();

		if ( $featured_id > 0 ) {
			$ids[] = $featured_id;
		}

		$include_gallery = ! empty( $options['includeGallery'] ) && (bool) $options['includeGallery'];

		if ( $include_gallery ) {
			foreach ( (array) $product->get_gallery_image_ids() as $gid ) {
				$gid = absint( $gid );
				if ( $gid > 0 ) {
					$ids[] = $gid;
				}
			}
		}

		return $ids;
	}
}
