<?php
/**
 * OpenAI provider.
 *
 * @package CatalogPilot\AiStudio
 */

namespace CatalogPilot\AiStudio\Providers;

defined( 'ABSPATH' ) || exit;

final class OpenAI_Provider extends Provider {

	const API_BASE = 'https://api.openai.com/v1';

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

	public function complete( $system, $user ) {
		if ( '' === $this->api_key ) {
			return new \WP_Error( 'cpais_missing_key', __( 'OpenAI API key is not configured.', 'catalogpilot-ai-studio-for-woocommerce' ) );
		}

		$body = array(
			'model'    => $this->model,
			'messages' => array(
				array( 'role' => 'system', 'content' => $system ),
				array( 'role' => 'user',   'content' => $user ),
			),
			'response_format' => array( 'type' => 'json_object' ),
			'temperature'     => 0.7,
		);

		$data = $this->request(
			self::API_BASE . '/chat/completions',
			array(
				'headers' => array(
					'Authorization' => 'Bearer ' . $this->api_key,
					'Content-Type'  => 'application/json',
				),
				'body' => wp_json_encode( $body ),
			)
		);

		if ( is_wp_error( $data ) ) {
			return $data;
		}

		$text = $data['choices'][0]['message']['content'] ?? '';
		return array(
			'text'  => $text,
			'usage' => array(
				'input_tokens'  => $data['usage']['prompt_tokens'] ?? 0,
				'output_tokens' => $data['usage']['completion_tokens'] ?? 0,
			),
		);
	}

	public function complete_vision( $system, $user, array $image_urls ) {
		if ( '' === $this->api_key ) {
			return new \WP_Error( 'cpais_missing_key', __( 'OpenAI API key is not configured.', 'catalogpilot-ai-studio-for-woocommerce' ) );
		}

		$user_content = array( array( 'type' => 'text', 'text' => (string) $user ) );
		foreach ( $image_urls as $url ) {
			$user_content[] = array(
				'type'      => 'image_url',
				'image_url' => array( 'url' => (string) $url ),
			);
		}

		$body = array(
			'model'       => $this->model,
			'messages'    => array(
				array( 'role' => 'system', 'content' => $system ),
				array( 'role' => 'user',   'content' => $user_content ),
			),
			'temperature' => 0.3,
			'max_tokens'  => 300,
		);

		$data = $this->request(
			self::API_BASE . '/chat/completions',
			array(
				'headers' => array(
					'Authorization' => 'Bearer ' . $this->api_key,
					'Content-Type'  => 'application/json',
				),
				'body'    => wp_json_encode( $body ),
			)
		);
		if ( is_wp_error( $data ) ) {
			return $data;
		}

		return array(
			'text'  => $data['choices'][0]['message']['content'] ?? '',
			'usage' => array(
				'input_tokens'  => $data['usage']['prompt_tokens']     ?? 0,
				'output_tokens' => $data['usage']['completion_tokens'] ?? 0,
			),
		);
	}

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