<?php
/**
 * Google Gemini text provider (native API).
 *
 * @package CatalogPilot\AiStudio
 */

namespace CatalogPilot\AiStudio\Providers;

defined( 'ABSPATH' ) || exit;

final class Gemini_Provider extends Provider {

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

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

	public function complete( $system, $user ) {
		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 ?: 'gemini-2.5-flash';
		$url   = self::API_BASE . '/models/' . rawurlencode( $model ) . ':generateContent?key=' . rawurlencode( $this->api_key );

		$body = array(
			'systemInstruction' => array(
				'parts' => array( array( 'text' => (string) $system ) ),
			),
			'contents' => array(
				array(
					'role'  => 'user',
					'parts' => array( array( 'text' => (string) $user ) ),
				),
			),
			'generationConfig' => array(
				'temperature'      => 0.7,
				'responseMimeType' => 'application/json',
			),
		);

		$data = $this->request(
			$url,
			array(
				'headers' => array( 'Content-Type' => 'application/json' ),
				'body'    => wp_json_encode( $body ),
			)
		);
		if ( is_wp_error( $data ) ) {
			return $data;
		}

		$text = '';
		foreach ( (array) ( $data['candidates'][0]['content']['parts'] ?? array() ) as $part ) {
			if ( isset( $part['text'] ) ) {
				$text .= $part['text'];
			}
		}

		return array(
			'text'  => $text,
			'usage' => array(
				'input_tokens'  => $data['usageMetadata']['promptTokenCount']     ?? 0,
				'output_tokens' => $data['usageMetadata']['candidatesTokenCount'] ?? 0,
			),
		);
	}

	public function complete_vision( $system, $user, array $image_urls ) {
		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 ?: 'gemini-2.5-flash';
		$url   = self::API_BASE . '/models/' . rawurlencode( $model ) . ':generateContent?key=' . rawurlencode( $this->api_key );

		$parts = array( array( 'text' => (string) $user ) );
		foreach ( $image_urls as $image_url ) {
			$fetched = wp_remote_get( $image_url, array( 'timeout' => 30 ) );
			if ( is_wp_error( $fetched ) ) {
				return $fetched;
			}
			$bytes = wp_remote_retrieve_body( $fetched );
			$mime  = wp_remote_retrieve_header( $fetched, 'content-type' ) ?: 'image/jpeg';
			$mime  = strtolower( trim( explode( ';', $mime )[0] ) );
			$parts[] = array(
				'inline_data' => array(
					'mime_type' => $mime,
					'data'      => base64_encode( $bytes ), // phpcs:ignore
				),
			);
		}

		$body = array(
			'systemInstruction' => array( 'parts' => array( array( 'text' => (string) $system ) ) ),
			'contents'          => array( array( 'role' => 'user', 'parts' => $parts ) ),
			'generationConfig'  => array( 'temperature' => 0.3 ),
		);

		$data = $this->request(
			$url,
			array(
				'headers' => array( 'Content-Type' => 'application/json' ),
				'body'    => wp_json_encode( $body ),
			)
		);
		if ( is_wp_error( $data ) ) {
			return $data;
		}

		$text = '';
		foreach ( (array) ( $data['candidates'][0]['content']['parts'] ?? array() ) as $p ) {
			if ( isset( $p['text'] ) ) {
				$text .= $p['text'];
			}
		}

		return array(
			'text'  => $text,
			'usage' => array(
				'input_tokens'  => $data['usageMetadata']['promptTokenCount']     ?? 0,
				'output_tokens' => $data['usageMetadata']['candidatesTokenCount'] ?? 0,
			),
		);
	}

	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(
			self::API_BASE . '/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;
	}
}
