<?php
/**
 * Google Gemini / Imagen image provider.
 *
 * @package CatalogPilot\AiStudio
 */

namespace CatalogPilot\AiStudio\Providers;

defined( 'ABSPATH' ) || exit;

final class Image_Gemini_Provider extends Image_Provider {

	const API = 'https://generativelanguage.googleapis.com/v1beta/models';

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

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

		$model  = $this->model ?: 'imagen-3.0-generate-002';
		$aspect = $opts['size'] ?? '1:1';
		$count  = max( 1, min( 4, (int) ( $opts['count'] ?? 1 ) ) );

		$body = array(
			'instances'  => array( array( 'prompt' => (string) $prompt ) ),
			'parameters' => array(
				'sampleCount' => $count,
				'aspectRatio' => $aspect,
			),
		);
		if ( ! empty( $opts['negative_prompt'] ) ) {
			$body['parameters']['negativePrompt'] = (string) $opts['negative_prompt'];
		}

		$url = self::API . '/' . rawurlencode( $model ) . ':predict?key=' . rawurlencode( $this->api_key );
		$result = $this->post_json( $url, $body );
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		$images = array();
		foreach ( (array) ( $result['predictions'] ?? array() ) as $pred ) {
			if ( ! empty( $pred['bytesBase64Encoded'] ) ) {
				$bytes = base64_decode( $pred['bytesBase64Encoded'], true ); // phpcs:ignore
				if ( false !== $bytes ) {
					$images[] = array(
						'bytes' => $bytes,
						'mime'  => $pred['mimeType'] ?? 'image/png',
					);
				}
			}
		}

		if ( empty( $images ) ) {
			return new \WP_Error( 'cpais_image_empty', __( 'Gemini 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', __( 'Google AI API key is required.', 'catalogpilot-ai-studio-for-woocommerce' ) );
		}
		$response = wp_remote_get(
			'https://generativelanguage.googleapis.com/v1beta/models?key=' . rawurlencode( $this->api_key ),
			array( 'timeout' => 15 )
		);
		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;
	}
}
