<?php
/**
 * OpenRouter AI provider.
 *
 * @package MasterQuiz
 * @since   1.0.0
 */

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

/**
 * Class MasterQuiz_Openrouter_Provider
 *
 * Implements AI calls to the OpenRouter API using wp_remote_post().
 * Uses the standard OpenAI-compatible chat completions endpoint.
 *
 * @since 1.0.0
 */
class MasterQuiz_Openrouter_Provider extends MasterQuiz_Ai_Provider {

	/**
	 * OpenRouter API endpoint.
	 *
	 * @var string
	 */
	const API_URL = 'https://openrouter.ai/api/v1/chat/completions';

	/**
	 * @inheritDoc
	 */
	public function call( $prompt, $schema = array(), $timeout = 60, $model = '' ) {
		if ( ! $this->has_api_key() ) {
			return new WP_Error( 'missing_key', esc_html__( 'OpenRouter API key is not configured.', 'masterquiz-ai' ) );
		}

		if ( empty( $model ) ) {
			$models = $this->get_models();
			$model  = $models[0];
		}

		// Append schema instruction to prompt if schema provided.
		$user_prompt = $prompt;
		if ( ! empty( $schema ) ) {
			$user_prompt .= "\n\nSTRICT JSON SCHEMA:\n" . wp_json_encode( $schema, JSON_PRETTY_PRINT );
		}

		$system_instruction = 'You are an expert academic quiz creator. You create ADVANCED, CONTENT-SPECIFIC questions that require deep understanding of source material. Always respond with valid JSON only, no additional text or markdown.';

		// Some models (e.g. Gemma) don't support system messages via certain
		// providers. Merge the system instruction into the user prompt instead.
		$messages = array(
			array(
				'role'    => 'user',
				'content' => $system_instruction . "\n\n" . $user_prompt,
			),
		);

		// Use fewer max tokens for shorter timeouts (fast mode).
		$max_tokens = $timeout <= 20 ? 4000 : 6000;

		$payload = array(
			'model'       => $model,
			'messages'    => $messages,
			'temperature' => 0.3,
			'max_tokens'  => $max_tokens,
		);

		$site_url = wp_parse_url( home_url(), PHP_URL_HOST );

		$response = wp_remote_post(
			self::API_URL,
			array(
				'timeout' => $timeout,
				'headers' => array(
					'Authorization' => 'Bearer ' . $this->api_key,
					'Content-Type'  => 'application/json',
					'Accept'        => 'application/json',
					'HTTP-Referer'  => $site_url ? $site_url : 'localhost',
					'X-Title'       => 'MasterQuiz AI',
				),
				'body'    => wp_json_encode( $payload ),
			)
		);

		if ( is_wp_error( $response ) ) {
			return new WP_Error( 'request_failed', $response->get_error_message() );
		}

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

		if ( isset( $body['error'] ) ) {
			$msg = is_array( $body['error'] ) ? ( $body['error']['message'] ?? 'Unknown error' ) : $body['error'];
			return new WP_Error( 'api_error', $msg );
		}

		if ( $code < 200 || $code >= 300 ) {
			return new WP_Error( 'api_error', 'OpenRouter HTTP ' . $code );
		}

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

		return new WP_Error( 'invalid_response', esc_html__( 'Invalid OpenRouter response structure.', 'masterquiz-ai' ) );
	}

	/**
	 * @inheritDoc
	 */
	public function get_provider_name() {
		return 'openrouter';
	}

	/**
	 * @inheritDoc
	 */
	public function get_models() {
		return array(
			'meta-llama/llama-3.3-70b-instruct:free',
			'nousresearch/hermes-3-llama-3.1-405b:free',
			'openai/gpt-oss-120b:free',
			'google/gemma-4-31b-it:free',
			'z-ai/glm-4.5-air:free',
		);
	}

	/**
	 * @inheritDoc
	 */
	public function test_connection() {
		if ( ! $this->has_api_key() ) {
			return new WP_Error( 'missing_key', esc_html__( 'API key not provided.', 'masterquiz-ai' ) );
		}

		$result = $this->call( 'Respond with the JSON: {"status":"ok"}', array(), 15, 'meta-llama/llama-3.3-70b-instruct:free' );

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

		return true;
	}
}
