<?php
/**
 * OpenRouter Provider
 *
 * Handles communication with OpenRouter API (100+ models).
 *
 * @package Askany
 * @since 1.0.0
 */

namespace Askany\Providers;

/**
 * OpenRouter provider class.
 */
class OpenRouterProvider extends AbstractProvider {
	/**
	 * {@inheritdoc}
	 */
	public function get_provider_name(): string {
		return 'openrouter';
	}

	/**
	 * {@inheritdoc}
	 */
	public function get_provider_display_name(): string {
		return 'OpenRouter';
	}

	/**
	 * {@inheritdoc}
	 */
	public function get_available_models(): array {
		// OpenRouter has 100+ models, these are just popular ones
		// Full list can be fetched via API
		return array(
			'openai/gpt-4o'                      => array(
				'name'               => 'GPT-4o (via OpenRouter)',
				'description'        => 'OpenAI GPT-4o',
				'max_tokens'         => 128000,
				'cost_per_1k_tokens' => 0.005,
			),
			'anthropic/claude-3.5-sonnet'        => array(
				'name'               => 'Claude 3.5 Sonnet (via OpenRouter)',
				'description'        => 'Anthropic Claude 3.5 Sonnet',
				'max_tokens'         => 200000,
				'cost_per_1k_tokens' => 0.003,
				'recommended'        => true,
			),
			'google/gemini-pro-1.5'              => array(
				'name'               => 'Gemini Pro 1.5 (via OpenRouter)',
				'description'        => 'Google Gemini Pro 1.5',
				'max_tokens'         => 1000000,
				'cost_per_1k_tokens' => 0.00125,
			),
			'meta-llama/llama-3.1-70b-instruct'  => array(
				'name'               => 'Llama 3.1 70B (via OpenRouter)',
				'description'        => 'Meta Llama 3.1 70B',
				'max_tokens'         => 131072,
				'cost_per_1k_tokens' => 0.00052,
			),
			'mistralai/mistral-large'            => array(
				'name'               => 'Mistral Large (via OpenRouter)',
				'description'        => 'Mistral Large',
				'max_tokens'         => 128000,
				'cost_per_1k_tokens' => 0.003,
			),
			'deepseek/deepseek-chat'             => array(
				'name'               => 'DeepSeek Chat (via OpenRouter)',
				'description'        => 'DeepSeek Chat',
				'max_tokens'         => 64000,
				'cost_per_1k_tokens' => 0.00014,
			),
			'x-ai/grok-beta'                     => array(
				'name'               => 'Grok Beta (via OpenRouter)',
				'description'        => 'X.AI Grok Beta',
				'max_tokens'         => 131072,
				'cost_per_1k_tokens' => 0.005,
			),
		);
	}

	/**
	 * {@inheritdoc}
	 */
	public function get_default_model(): string {
		return 'anthropic/claude-3.5-sonnet';
	}

	/**
	 * {@inheritdoc}
	 */
	public function get_default_endpoint(): string {
		return 'https://openrouter.ai/api/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,
			'HTTP-Referer'       => home_url(),
			'X-Title'            => get_bloginfo( 'name' ),
		);

		$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'],
		);
	}

	/**
	 * Fetch available models from OpenRouter API.
	 *
	 * @return array|false Array of models or false on failure.
	 */
	public function fetch_available_models() {
		$response = wp_remote_get(
			'https://openrouter.ai/api/v1/models',
			array(
				'headers' => array(
					'Authorization' => 'Bearer ' . $this->api_key,
				),
				'timeout' => 15,
			)
		);

		if ( is_wp_error( $response ) ) {
			$this->last_error = $response->get_error_message();
			return false;
		}

		$body = wp_remote_retrieve_body( $response );
		$data = json_decode( $body, true );

		if ( isset( $data['data'] ) && is_array( $data['data'] ) ) {
			return $data['data'];
		}

		return false;
	}
}
