<?php
/**
 * OpenAI image provider (gpt-image-1, dall-e-3, dall-e-2).
 *
 * @package CatalogPilot\AiStudio
 */

namespace CatalogPilot\AiStudio\Providers;

defined( 'ABSPATH' ) || exit;

final class Image_OpenAI_Provider extends Image_Provider {

	const API = 'https://api.openai.com/v1/images/generations';

	public function id() {
		return 'openai';
	}

	public function generate( $prompt, array $opts = array() ) {
		if ( '' === $this->api_key ) {
			return new \WP_Error( 'cpais_missing_key', __( 'OpenAI API key is required.', 'catalogpilot-ai-studio-for-woocommerce' ) );
		}

		$model = $this->model ?: 'gpt-image-1';
		$size  = $opts['size'] ?? '1024x1024';
		$count = max( 1, min( 4, (int) ( $opts['count'] ?? 1 ) ) );

		$body = array(
			'model'  => $model,
			'prompt' => (string) $prompt,
			'n'      => $count,
			'size'   => $size,
		);

		if ( 'dall-e-3' === $model ) {
			$body['response_format'] = 'b64_json';
			$body['n']               = 1; // DALL-E 3 only supports n=1.
			if ( isset( $opts['quality'] ) ) {
				$body['quality'] = $opts['quality']; // 'standard' | 'hd'
			}
			if ( isset( $opts['style'] ) ) {
				$body['style'] = $opts['style']; // 'natural' | 'vivid'
			}
		} elseif ( 'dall-e-2' === $model ) {
			$body['response_format'] = 'b64_json';
		}
		// gpt-image-1 always returns b64_json.

		$result = $this->post_json(
			self::API,
			$body,
			array( 'Authorization' => 'Bearer ' . $this->api_key )
		);
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		$images = array();
		foreach ( (array) ( $result['data'] ?? array() ) as $item ) {
			if ( ! empty( $item['b64_json'] ) ) {
				$bytes = base64_decode( $item['b64_json'], true ); // phpcs:ignore
				if ( false !== $bytes ) {
					$images[] = array( 'bytes' => $bytes, 'mime' => 'image/png' );
				}
			} elseif ( ! empty( $item['url'] ) ) {
				$fetched = self::fetch_url_bytes( $item['url'] );
				if ( ! is_wp_error( $fetched ) ) {
					$images[] = $fetched;
				}
			}
		}

		if ( empty( $images ) ) {
			return new \WP_Error( 'cpais_image_empty', __( 'Provider returned no images.', 'catalogpilot-ai-studio-for-woocommerce' ) );
		}

		return $images;
	}

	public function test_connection() {
		if ( '' === $this->api_key ) {
			return new \WP_Error( 'cpais_missing_key', __( 'OpenAI API key is required.', 'catalogpilot-ai-studio-for-woocommerce' ) );
		}
		$response = wp_remote_get(
			'https://api.openai.com/v1/models',
			array(
				'timeout' => 15,
				'headers' => array( 'Authorization' => 'Bearer ' . $this->api_key ),
			)
		);
		if ( is_wp_error( $response ) ) {
			return $response;
		}
		$code = wp_remote_retrieve_response_code( $response );
		if ( 200 !== $code ) {
			return new \WP_Error( 'cpais_auth_failed', __( 'Authentication failed.', 'catalogpilot-ai-studio-for-woocommerce' ), array( 'status' => $code ) );
		}
		return true;
	}
}
