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

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

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

	/**
	 * Groq API endpoint.
	 *
	 * @var string
	 */
	const API_URL = 'https://api.groq.com/openai/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__( 'Groq API key is not configured.', 'masterquiz-ai' ) );
		}

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

		// Strip groq/ prefix if present.
		$model = str_replace( 'groq/', '', $model );

		// Append schema instruction to prompt if schema provided.
		$user_prompt = $prompt;
		if ( ! empty( $schema ) ) {
			$user_prompt .= "\nRespond ONLY with JSON matching schema: " . wp_json_encode( $schema );
		}

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

		$payload = array(
			'model'       => $model,
			'messages'    => array(
				array(
					'role'    => 'system',
					'content' => '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.',
				),
				array(
					'role'    => 'user',
					'content' => $user_prompt,
				),
			),
			'temperature' => 0.3,
			'max_tokens'  => $max_tokens,
		);

		$response = wp_remote_post(
			self::API_URL,
			array(
				'timeout' => $timeout,
				'headers' => array(
					'Authorization' => 'Bearer ' . $this->api_key,
					'Content-Type'  => 'application/json',
				),
				'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', 'Groq HTTP ' . $code );
		}

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

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

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

	/**
	 * @inheritDoc
	 */
	public function get_models() {
		return array(
			'openai/gpt-oss-20b',
			'openai/gpt-oss-120b',
		);
	}

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

		$last_error = null;
		foreach ( $this->get_models() as $model ) {
			$result = $this->call( 'Respond with the JSON: {"status":"ok"}', array(), 20, $model );
			if ( ! is_wp_error( $result ) ) {
				return true;
			}
			$last_error = $result;
		}

		return $last_error instanceof WP_Error
			? $last_error
			: new WP_Error( 'test_failed', esc_html__( 'Groq connection test failed.', 'masterquiz-ai' ) );
	}
}
