<?php

namespace WeDevs\Wpuf\Pro\AI_Review\Providers;

/**
 * OpenAI AI Provider
 *
 * Handles API calls to OpenAI's AI services
 *
 * @since 4.2.9
 */
class OpenAI_Provider extends Abstract_Provider {

	/**
	 * Make API call to OpenAI
	 *
	 * @since 4.2.9
	 * @param string $endpoint API endpoint
	 * @param string $api_key  API key
	 * @param string $model    Model to use
	 * @param string $prompt   Review prompt
	 * @return string API response
	 * @throws \Exception
	 */
	public function make_api_call( $endpoint, $api_key, $model, $prompt ) {
		$headers = [
			'Authorization' => 'Bearer ' . $api_key,
			'Content-Type'  => 'application/json',
		];

		$args = [
			'headers' => $headers,
			'body'    => json_encode( $this->build_request_body( $prompt ) ),
		];

		$response = $this->make_request( $endpoint, $args );

		$body = wp_remote_retrieve_body( $response );

		return $this->parse_response( $body );
	}

	/**
	 * Validate OpenAI API key format
	 *
	 * OpenAI API keys start with 'sk-' and are typically 51 characters
	 *
	 * @since 4.2.9
	 * @param string $api_key API key to validate
	 * @return bool True if valid format
	 */
	public function validate_api_key( $api_key ) {
		// OpenAI API keys start with 'sk-'
		return ! empty( $api_key ) && preg_match( '/^sk-[a-zA-Z0-9]{32,}$/', $api_key );
	}

	/**
	 * Get request headers for OpenAI API
	 *
	 * @since 4.2.9
	 * @return array Request headers
	 */
	protected function get_request_headers() {
		return [
			'Authorization' => 'Bearer ' . $this->api_key,
			'Content-Type'  => 'application/json',
		];
	}

	/**
	 * Parse OpenAI API response
	 *
	 * @since 4.2.9
	 * @param string $response_body Response body
	 * @return string Parsed response content
	 * @throws \Exception
	 */
	protected function parse_response( $response_body ) {
		$decoded = json_decode( $response_body, true );

		if ( isset( $decoded['choices'][0]['message']['content'] ) ) {
			return $decoded['choices'][0]['message']['content'];
		}

		throw new \Exception( 'Invalid OpenAI API response' );
	}

	/**
	 * Build request body for OpenAI API
	 *
	 * @since 4.2.9
	 * @param string $prompt Review prompt
	 * @return array Request body
	 */
	protected function build_request_body( $prompt ) {
		return [
			'model'       => $this->model,
			'messages'    => [
				[
					'role'    => 'user',
					'content' => $prompt,
				],
			],
			'max_tokens'  => $this->max_tokens,
			'temperature' => $this->temperature,
		];
	}
}
