<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! class_exists( 'SftcyWordaiXaiApi' ) ) :

class SftcyWordaiXaiApi {

	protected static $API_KEY = null;

	public static $AI_COMPLETION_EP = 'https://api.x.ai/v1/chat/completions';
	public static $AI_IMAGE_EP      = 'https://api.x.ai/v1/images/generations';
	public static $MODEL            = 'grok-4.5';
	public static $IMAGE_MODEL      = 'grok-imagine-image-quality';
	public static $STREAM           = null;
	public static $output           = [];

	public function __construct() {
		self::ensure_api_key();
	}

	protected static function ensure_api_key() {
		if ( ! is_null( self::$API_KEY ) ) {
			return;
		}

		if ( ! class_exists( 'SftcyWordaiBase' ) ) {
			return;
		}

		$data = SftcyWordaiBase::sc_wordai_get_current_api_settings();

		self::$API_KEY = ! empty( $data['wordai-xai-api-key-data'] )
			? trim( (string) $data['wordai-xai-api-key-data'] )
			: null;
	}

	public static function sc_xai_streaming_status() {
		$data = class_exists( 'SftcyWordaiBase' ) ? SftcyWordaiBase::sc_wordai_get_current_api_settings() : [];
		return ( isset( $data['sc-wordai-streaming'] ) && intval( $data['sc-wordai-streaming'] ) === 1 );
	}

	public static function sc_curl_add_streaming_hook() {
		add_action( 'http_api_curl', [ __CLASS__, 'sc_wordai_xai_stream_response' ], 10, 3 );
	}

	public static function sc_curl_remove_streaming_hook() {
		remove_action( 'http_api_curl', [ __CLASS__, 'sc_wordai_xai_stream_response' ], 10 );
	}

	public static function sc_wordai_xai_stream_response( $handle, $r = [], $url = '' ) {
		if ( self::$STREAM !== true ) {
			return;
		}

		@ob_end_clean();
		@ob_start();

		curl_setopt( $handle, CURLOPT_FOLLOWLOCATION, 1 );
		curl_setopt(
			$handle,
			CURLOPT_WRITEFUNCTION,
			function ( $curl, $data ) {
				echo $data;
				@ob_flush();
				flush();
				return strlen( $data );
			}
		);
	}

	public static function set_xai_params( $prompt = '' ) {
		$data = class_exists( 'SftcyWordaiBase' )
			? SftcyWordaiBase::sc_wordai_get_current_api_settings()
			: [];

		$model = class_exists( 'SftcyWordaiXaiSettings' )
			? SftcyWordaiXaiSettings::normalize_xai_model_slug( $data['sc-wordai-xai-model-slug'] ?? '' )
			: self::$MODEL;

		$params = [
			'model'       => $model,
			'messages'    => [
				[
					'role'    => 'user',
					'content' => trim( (string) $prompt ),
				],
			],
			'temperature' => isset( $data['sc-wordai-temperature'] ) ? max( 0.0, min( 2.0, floatval( $data['sc-wordai-temperature'] ) ) ) : 0.4,
			'top_p'       => isset( $data['sc-wordai-top-p'] ) ? max( 0.0, min( 1.0, floatval( $data['sc-wordai-top-p'] ) ) ) : 0.9,
			'stream'      => self::sc_xai_streaming_status(),
		];

		if ( ! empty( $data['sc-wordai-max-tokens'] ) ) {
			$params['max_tokens'] = max( 64, intval( $data['sc-wordai-max-tokens'] ) );
		}

		if ( ! empty( $data['sc-wordai-stop-input'] ) ) {
			$params['stop'] = trim( (string) $data['sc-wordai-stop-input'] );
		}

		return $params;
	}

	private static function send_chat_request( array $body, $stream = false ) {
		self::$output = [];
		self::$output['wordAIRequestParams'] = $body;

		self::ensure_api_key();

		if ( empty( self::$API_KEY ) ) {
			self::$output['status']              = 'fail';
			self::$output['comment']             = 'Valid API Key missing.';
			self::$output['wordAIAPIKeyMissing'] = __( 'Valid xAI Grok API Key required.', 'wordai' );
			return self::$output;
		}

		$body['stream'] = (bool) $stream;

		if ( $stream ) {
			self::$STREAM = true;
			self::sc_curl_add_streaming_hook();
		} else {
			self::$STREAM = false;
		}

		$response = wp_remote_post(
			self::$AI_COMPLETION_EP,
			[
				'headers'     => [
					'Authorization' => 'Bearer ' . self::$API_KEY,
					'Content-Type'  => 'application/json; charset=UTF-8',
				],
				'timeout'     => 90,
				'httpversion' => '1.1',
				'sslverify'   => class_exists( 'SftcyWordaiBase' ) ? SftcyWordaiBase::sc_wordai_should_verify_ssl() : true,
				'data_format' => 'body',
				'body'        => wp_json_encode( $body ),
			]
		);

		if ( $stream ) {
			self::sc_curl_remove_streaming_hook();
			exit;
		}

		if ( is_wp_error( $response ) ) {
			self::$output['status']       = 'fail';
			self::$output['errorMessage'] = $response->get_error_message();
			return self::$output;
		}

		$decoded   = json_decode( wp_remote_retrieve_body( $response ), true );
		$http_code = (int) wp_remote_retrieve_response_code( $response );

		self::$output['responseBody'] = $decoded;

		if ( $http_code < 200 || $http_code >= 300 ) {
			self::$output['status']       = 'fail';
			self::$output['errorMessage'] = $decoded['error']['message'] ?? __( 'xAI Grok request failed.', 'wordai' );
			self::$output['errorType']    = $decoded['error']['type'] ?? 'xai_error';
			return self::$output;
		}

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

		if ( trim( $text ) === '' ) {
			self::$output['status']       = 'fail';
			self::$output['errorMessage'] = __( 'xAI Grok returned no text response.', 'wordai' );
			return self::$output;
		}

		self::$output['status']       = 'success';
		self::$output['responseText'] = wp_kses_post( $text );
		self::$output['model']        = esc_html( $body['model'] ?? self::$MODEL );

		return self::$output;
	}

	public static function create_content( $api_params = [], $stream = false ) {
		if ( empty( $api_params['messages'] ) || ! is_array( $api_params['messages'] ) ) {
			return [
				'status'       => 'fail',
				'errorMessage' => __( 'Invalid xAI Grok parameters received.', 'wordai' ),
				'errorType'    => 'xai_params_error',
			];
		}

		return self::send_chat_request( $api_params, (bool) $stream );
	}

	public static function create_chat_reply(
		$user_prompt,
		$model,
		$temperature,
		$system_message = '',
		$stream = false,
		$assistant_context = ''
	) {
		$user_prompt = trim( (string) $user_prompt );
		if ( $user_prompt === '' ) {
			return [
				'status' => 'error',
				'reply'  => __( 'Empty message.', 'wordai' ),
			];
		}

		$messages = [];
		if ( $system_message !== '' ) {
			$messages[] = [
				'role'    => 'system',
				'content' => trim( (string) $system_message ),
			];
		}

		if ( $assistant_context !== '' ) {
			$messages[] = [
				'role'    => 'system',
				'content' => "Website context:\n" . trim( (string) $assistant_context ),
			];
		}

		$messages[] = [
			'role'    => 'user',
			'content' => $user_prompt,
		];

		$body = [
			'model'       => class_exists( 'SftcyWordaiXaiSettings' ) ? SftcyWordaiXaiSettings::normalize_xai_model_slug( $model ) : ( $model ?: self::$MODEL ),
			'temperature' => max( 0.0, min( 2.0, floatval( $temperature ) ) ),
			'messages'    => $messages,
			'max_tokens'  => 2048,
		];

		$response = self::send_chat_request( $body, (bool) $stream );

		if ( ! is_array( $response ) || ( $response['status'] ?? '' ) !== 'success' ) {
			return [
				'status' => 'error',
				'reply'  => $response['errorMessage'] ?? __( 'xAI Grok request failed.', 'wordai' ),
			];
		}

		return [
			'status' => 'success',
			'reply'  => $response['responseText'] ?? '',
			'model'  => $body['model'],
		];
	}

	public static function set_xai_image_params( $prompt = '' ) {
		$data = class_exists( 'SftcyWordaiBase' )
			? SftcyWordaiBase::sc_wordai_get_current_image_settings()
			: [];

		$model = class_exists( 'SftcyWordaiXaiSettings' )
			? SftcyWordaiXaiSettings::normalize_xai_image_model_slug( $data['sc-wordai-xai-image-model-slug'] ?? '' )
			: self::$IMAGE_MODEL;

		return [
			'model'           => $model,
			'prompt'          => trim( (string) $prompt ),
			'n'               => 1,
			'response_format' => 'b64_json',
			'aspect_ratio'    => class_exists( 'SftcyWordaiXaiSettings' ) ? SftcyWordaiXaiSettings::normalize_xai_image_aspect_ratio( $data['sc-wordai-xai-image-aspect-ratio'] ?? '' ) : 'auto',
			'resolution'      => class_exists( 'SftcyWordaiXaiSettings' ) ? SftcyWordaiXaiSettings::normalize_xai_image_resolution( $data['sc-wordai-xai-image-resolution'] ?? '' ) : '1k',
		];
	}

	public static function generate_image( $api_params = [] ) {
		self::ensure_api_key();

		if ( empty( self::$API_KEY ) ) {
			return [
				'status'              => 'fail',
				'wordAIAPIKeyMissing' => __( 'Valid xAI Grok API Key required.', 'wordai' ),
				'errorMessage'        => __( 'Valid xAI Grok API Key required.', 'wordai' ),
			];
		}

		$response = wp_remote_post(
			self::$AI_IMAGE_EP,
			[
				'headers'     => [
					'Authorization' => 'Bearer ' . self::$API_KEY,
					'Content-Type'  => 'application/json; charset=UTF-8',
				],
				'timeout'     => 120,
				'httpversion' => '1.1',
				'sslverify'   => class_exists( 'SftcyWordaiBase' ) ? SftcyWordaiBase::sc_wordai_should_verify_ssl() : true,
				'data_format' => 'body',
				'body'        => wp_json_encode( $api_params ),
			]
		);

		if ( is_wp_error( $response ) ) {
			return [
				'status'       => 'fail',
				'errorMessage' => $response->get_error_message(),
			];
		}

		$decoded   = json_decode( wp_remote_retrieve_body( $response ), true );
		$http_code = (int) wp_remote_retrieve_response_code( $response );

		if ( $http_code < 200 || $http_code >= 300 || ! is_array( $decoded ) ) {
			return [
				'status'       => 'fail',
				'errorMessage' => is_array( $decoded ) ? ( $decoded['error']['message'] ?? __( 'xAI Grok image request failed.', 'wordai' ) ) : __( 'xAI Grok image request failed.', 'wordai' ),
				'responseBody' => $decoded,
			];
		}

		if ( empty( $decoded['data'] ) || ! is_array( $decoded['data'] ) ) {
			return [
				'status'       => 'fail',
				'errorMessage' => __( 'xAI Grok returned no generated images.', 'wordai' ),
				'responseBody' => $decoded,
			];
		}

		return [
			'status'            => 'success',
			'responseImageData' => $decoded['data'],
			'responseBody'      => $decoded,
			'model'             => $api_params['model'] ?? self::$IMAGE_MODEL,
		];
	}
}

endif;
