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

class SftcyWordaiAgentXai {

	const PROVIDER                = 'xai';
	const DEFAULT_EMBEDDING_MODEL = 'grok-embedding-small';
	const EMBEDDING_ENDPOINT      = 'https://api.x.ai/v1/embeddings';

	public static function embedding_models() {
		return [
			'grok-embedding-small' => 'Grok Embedding Small',
		];
	}

	public static function normalize_embedding_model( $model = '' ) {
		$model = trim( (string) $model );
		return $model === self::DEFAULT_EMBEDDING_MODEL ? $model : self::DEFAULT_EMBEDDING_MODEL;
	}

	public static function get_api_key() {
		if ( ! class_exists( 'SftcyWordaiBase' ) ) {
			return '';
		}

		$settings = SftcyWordaiBase::sc_wordai_get_current_api_settings();
		return ! empty( $settings['wordai-xai-api-key-data'] ) ? trim( (string) $settings['wordai-xai-api-key-data'] ) : '';
	}

	public static function is_configured() {
		return self::get_api_key() !== '';
	}

	public static function create_embeddings( $texts = [], $model = self::DEFAULT_EMBEDDING_MODEL, $input_type = 'document' ) {
		$texts = array_values(
			array_filter(
				array_map(
					static function( $text ) {
						return trim( wp_strip_all_tags( (string) $text ) );
					},
					(array) $texts
				),
				static function( $text ) {
					return $text !== '';
				}
			)
		);

		if ( empty( $texts ) ) {
			return [
				'status'      => 'fail',
				'feedbackMsg' => __( 'No valid text provided for xAI Grok embedding.', 'wordai' ),
			];
		}

		$api_key = self::get_api_key();
		if ( $api_key === '' ) {
			return [
				'status'      => 'fail',
				'feedbackMsg' => __( 'xAI Grok API key is missing. Save it under API Settings before indexing xAI content.', 'wordai' ),
			];
		}

		$model = self::normalize_embedding_model( $model );

		$response = wp_remote_post(
			self::EMBEDDING_ENDPOINT,
			[
				'headers'   => [
					'Authorization' => 'Bearer ' . $api_key,
					'Content-Type'  => 'application/json',
				],
				'body'      => wp_json_encode(
					[
						'input' => $texts,
						'model' => $model,
					]
				),
				'timeout'   => 90,
				'sslverify' => self::should_verify_ssl(),
			]
		);

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

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

		if ( $code < 200 || $code >= 300 || ! is_array( $json ) ) {
			$error_message = __( 'xAI Grok embedding request failed.', 'wordai' );
			if ( is_array( $json ) ) {
				if ( ! empty( $json['error']['message'] ) ) {
					$error_message = (string) $json['error']['message'];
				} elseif ( ! empty( $json['error'] ) && is_string( $json['error'] ) ) {
					$error_message = (string) $json['error'];
				} elseif ( ! empty( $json['message'] ) ) {
					$error_message = (string) $json['message'];
				}
			}
			$error_message = preg_replace( '/team\s+[0-9a-f-]{36}/i', 'team account', $error_message );

			return [
				'status'      => 'fail',
				'feedbackMsg' => $error_message,
			];
		}

		$vectors = [];
		if ( isset( $json['data'] ) && is_array( $json['data'] ) ) {
			foreach ( $json['data'] as $item ) {
				if ( isset( $item['embedding'] ) && is_array( $item['embedding'] ) ) {
					$vectors[] = $item['embedding'];
				}
			}
		}

		if ( empty( $vectors ) ) {
			return [
				'status'      => 'fail',
				'feedbackMsg' => __( 'xAI Grok returned no embeddings.', 'wordai' ),
			];
		}

		return [
			'status'       => 'success',
			'feedbackMsg'  => __( 'xAI Grok embeddings created successfully.', 'wordai' ),
			'embeddings'   => $vectors,
			'provider'     => self::PROVIDER,
			'model'        => $model,
			'total_tokens' => isset( $json['usage']['total_tokens'] ) ? (int) $json['usage']['total_tokens'] : 0,
		];
	}

	public static function chunk_text( $text = '', $chunk_size = 500 ) {
		return SftcyWordaiAgentOpenai::chunk_text( $text, $chunk_size );
	}

	public static function estimate_cost( $total_words = 0, $model = self::DEFAULT_EMBEDDING_MODEL ) {
		if ( $total_words <= 0 ) {
			return [
				'status'      => 'fail',
				'feedbackMsg' => __( 'No valid words provided for xAI Grok embedding estimation.', 'wordai' ),
			];
		}

		$tokens = (int) ceil( $total_words / 0.75 );

		return [
			'status'         => 'success',
			'total_tokens'   => $tokens,
			'estimated_cost' => __( 'Check xAI billing for final embedding cost.', 'wordai' ),
			'provider'       => self::PROVIDER,
			'model'          => self::normalize_embedding_model( $model ),
			'feedbackMsg'    => __( 'xAI Grok embedding token estimate prepared successfully.', 'wordai' ),
		];
	}

	public static function compute_chunk_hash( $chunk_text ) {
		return SftcyWordaiAgentOpenai::compute_chunk_hash( $chunk_text );
	}

	public static function store_embedding( $source_id, $chunk_text, $embedding, $model = self::DEFAULT_EMBEDDING_MODEL ) {
		global $wpdb;

		$model      = self::normalize_embedding_model( $model );
		$table      = $wpdb->prefix . 'wordai_agent_embeddings';
		$chunk_hash = self::compute_chunk_hash( $chunk_text );

		$exists = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT id FROM {$table}
				 WHERE source_id=%d AND provider=%s AND model=%s AND chunk_hash=%s
				 LIMIT 1",
				$source_id,
				self::PROVIDER,
				$model,
				$chunk_hash
			)
		);

		if ( $exists ) {
			return;
		}

		$wpdb->insert(
			$table,
			[
				'source_id'  => $source_id,
				'chunk_text' => maybe_serialize( $chunk_text ),
				'embedding'  => maybe_serialize( $embedding ),
				'model'      => $model,
				'provider'   => self::PROVIDER,
				'chunk_hash' => $chunk_hash,
				'created_at' => current_time( 'mysql' ),
			],
			[ '%d', '%s', '%s', '%s', '%s', '%s', '%s' ]
		);
	}

	private static function should_verify_ssl() {
		if ( class_exists( 'SftcyWordaiBase' ) && method_exists( 'SftcyWordaiBase', 'sc_wordai_should_verify_ssl' ) ) {
			return (bool) SftcyWordaiBase::sc_wordai_should_verify_ssl();
		}

		return true;
	}
}
