<?php
/**
 * Answyr — OpenAI provider.
 *
 * Uses the Chat Completions API. OpenAI folds the system prompt into the
 * messages array (role: system), unlike Anthropic which takes it separately —
 * the provider contract passes $system distinctly so each provider adapts.
 *
 * @package Answyr
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

final class Answyr_Provider_OpenAI extends Answyr_AI_Provider {

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

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

	public function label(): string {
		return __( 'OpenAI (GPT)', 'answyr' );
	}

	public function key_url(): string {
		return 'https://platform.openai.com/api-keys';
	}

	public function models(): array {
		return array(
			'gpt-4o'      => 'GPT-4o (balanced)',
			'gpt-4o-mini' => 'GPT-4o mini (fast/cheap)',
			'gpt-4.1'     => 'GPT-4.1 (best quality)',
		);
	}

	public function default_model(): string {
		return 'gpt-4o';
	}

	public function complete( string $system, array $messages, array $opts ): string {
		// Prepend the system prompt as a system-role message.
		$payload_messages = array_merge(
			array(
				array(
					'role'    => 'system',
					'content' => $system,
				),
			),
			array_map(
				static function ( $m ) {
					return array(
						'role'    => $m['role'] ?? 'user',
						'content' => $m['content'] ?? '',
					);
				},
				$messages
			)
		);

		$payload = array(
			'model'       => $this->opt( $opts, 'model', $this->default_model() ),
			'max_tokens'  => (int) $this->opt( $opts, 'max_tokens', 1500 ),
			'temperature' => (float) $this->opt( $opts, 'temperature', 0.3 ),
			'messages'    => $payload_messages,
		);

		$response = wp_remote_post(
			self::API_BASE . '/chat/completions',
			array(
				'headers' => array(
					'Content-Type'  => 'application/json',
					'Authorization' => 'Bearer ' . (string) $this->opt( $opts, 'api_key', '' ),
				),
				'body'    => wp_json_encode( $payload ),
				'timeout' => 60,
			)
		);

		if ( is_wp_error( $response ) ) {
			throw new \RuntimeException( esc_html( $response->get_error_message() ) );
		}

		$code = wp_remote_retrieve_response_code( $response );
		$body = json_decode( wp_remote_retrieve_body( $response ), true );

		if ( 200 !== (int) $code ) {
			$msg = $body['error']['message'] ?? wp_remote_retrieve_response_message( $response );
			throw new \RuntimeException(
				/* translators: 1: HTTP code, 2: error message */
				esc_html( sprintf( __( 'OpenAI API error (%1$d): %2$s', 'answyr' ), $code, $msg ) )
			);
		}

		return (string) ( $body['choices'][0]['message']['content'] ?? '' );
	}

	public function test_connection( string $api_key ): bool {
		$response = wp_remote_post(
			self::API_BASE . '/chat/completions',
			array(
				'headers' => array(
					'Content-Type'  => 'application/json',
					'Authorization' => 'Bearer ' . $api_key,
				),
				'body'    => wp_json_encode(
					array(
						'model'      => 'gpt-4o-mini',
						'max_tokens' => 10,
						'messages'   => array(
							array(
								'role'    => 'user',
								'content' => 'Say "ok".',
							),
						),
					)
				),
				'timeout' => 15,
			)
		);

		return ! is_wp_error( $response ) && 200 === (int) wp_remote_retrieve_response_code( $response );
	}
}
