<?php
/**
 * X.AI Grok Provider
 *
 * Handles communication with X.AI Grok API.
 *
 * @package Askany
 * @since 1.0.0
 */

namespace Askany\Providers;

/**
 * Grok provider class.
 */
class GrokProvider extends AbstractProvider {
	/**
	 * {@inheritdoc}
	 */
	public function get_provider_name(): string {
		return 'grok';
	}

	/**
	 * {@inheritdoc}
	 */
	public function get_provider_display_name(): string {
		return 'X.AI Grok';
	}

	/**
	 * {@inheritdoc}
	 */
	public function get_available_models(): array {
		return array(
			'grok-beta'                  => array(
				'name'               => 'Grok Beta',
				'description'        => 'Latest Grok model',
				'max_tokens'         => 131072,
				'cost_per_1k_tokens' => 0.005,
				'recommended'        => true,
			),
			'grok-vision-beta'           => array(
				'name'               => 'Grok Vision Beta',
				'description'        => 'Grok with vision capabilities',
				'max_tokens'         => 8192,
				'cost_per_1k_tokens' => 0.005,
			),
			'grok-2-1212'                => array(
				'name'               => 'Grok 2',
				'description'        => 'Previous generation',
				'max_tokens'         => 131072,
				'cost_per_1k_tokens' => 0.002,
			),
			'grok-2-vision-1212'         => array(
				'name'               => 'Grok 2 Vision',
				'description'        => 'Grok 2 with vision',
				'max_tokens'         => 8192,
				'cost_per_1k_tokens' => 0.002,
			),
		);
	}

	/**
	 * {@inheritdoc}
	 */
	public function get_default_model(): string {
		return 'grok-beta';
	}

	/**
	 * {@inheritdoc}
	 */
	public function get_default_endpoint(): string {
		return 'https://api.x.ai/v1/chat/completions';
	}

	/**
	 * {@inheritdoc}
	 */
	public function send_chat_request( array $messages, array $options = array() ) {
		$defaults = array(
			'model'             => $this->get_default_model(),
			'temperature'       => 0.3,
			'max_tokens'        => 800,
			'frequency_penalty' => 0.3,
		);

		$params = array_merge( $defaults, $options );
		$params['messages'] = $messages;

		$headers = array(
			'Authorization' => 'Bearer ' . $this->api_key,
		);

		$data = $this->make_request( $this->api_url, $params, $headers );

		if ( ! $data ) {
			return false;
		}

		// Check for error in response
		if ( isset( $data['error'] ) ) {
			$error_msg = isset( $data['error']['message'] ) ? $data['error']['message'] : 'Unknown error';
			$this->last_error = $error_msg;
			return false;
		}

		if ( ! isset( $data['choices'][0]['message']['content'] ) ) {
			$this->last_error = 'Unexpected response structure';
			return false;
		}

		return array(
			'text' => $data['choices'][0]['message']['content'],
		);
	}
}
