<?php
/**
 * WordPress AI Client integration.
 *
 * @package Maca_Tjatt
 */

defined( 'ABSPATH' ) || exit;

/**
 * Class Maca_Tjatt_AI_Client
 */
class Maca_Tjatt_AI_Client {

	/**
	 * Provider IDs checked when detecting a connected AI service.
	 *
	 * @var array<int, string>
	 */
	private static $provider_ids = array( 'openai', 'anthropic', 'google' );

	/**
	 * @return bool
	 */
	public static function is_available() {
		if ( ! function_exists( 'wp_ai_client_prompt' ) ) {
			return false;
		}

		if ( function_exists( 'wp_supports_ai' ) && ! wp_supports_ai() ) {
			return false;
		}

		if ( self::has_configured_provider() ) {
			return true;
		}

		$builder = wp_ai_client_prompt( 'test' );

		if ( ! is_object( $builder ) || ! method_exists( $builder, 'is_supported_for_text_generation' ) ) {
			return false;
		}

		return (bool) $builder->is_supported_for_text_generation();
	}

	/**
	 * @return bool
	 */
	private static function has_configured_provider() {
		if ( ! class_exists( 'WordPress\AiClient\AiClient' ) ) {
			return false;
		}

		foreach ( self::$provider_ids as $provider_id ) {
			try {
				if ( \WordPress\AiClient\AiClient::isConfigured( $provider_id ) ) {
					return true;
				}
			} catch ( \Throwable $e ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
				continue;
			}
		}

		return false;
	}

	/**
	 * @return string
	 */
	public static function get_connectors_admin_url() {
		return admin_url( 'options-general.php?page=connectors' );
	}

	/**
	 * @return string
	 */
	public static function get_unavailable_message() {
		return __( 'WordPress AI is not configured. Install and connect an AI provider under Settings → Connectors.', 'maca-tjatt' );
	}

	/**
	 * @param string                            $user_message       Final user message.
	 * @param string                            $system_instruction System prompt.
	 * @param array<int, array<string, string>> $history            Prior chat turns.
	 * @param string                            $model_preference   Optional preferred model slug.
	 * @return string|WP_Error
	 */
	public static function generate_chat( $user_message, $system_instruction, $history = array(), $model_preference = '' ) {
		if ( ! self::is_available() ) {
			return new WP_Error( 'maca_tjatt_ai_unavailable', self::get_unavailable_message() );
		}

		$user_message       = trim( (string) $user_message );
		$system_instruction = trim( (string) $system_instruction );

		if ( '' === $user_message ) {
			return new WP_Error( 'maca_tjatt_empty', __( 'Please enter a question.', 'maca-tjatt' ) );
		}

		$answer = self::request_chat( $user_message, $system_instruction, $history, $model_preference );

		if ( is_wp_error( $answer ) && '' !== trim( (string) $model_preference ) ) {
			$answer = self::request_chat( $user_message, $system_instruction, $history, '' );
		}

		return $answer;
	}

	/**
	 * @param string                            $user_message       Final user message.
	 * @param string                            $system_instruction System prompt.
	 * @param array<int, array<string, string>> $history            Prior chat turns.
	 * @param string                            $model_preference   Optional preferred model slug.
	 * @return string|WP_Error
	 */
	private static function request_chat( $user_message, $system_instruction, $history, $model_preference ) {
		$builder = wp_ai_client_prompt( $user_message )
			->using_system_instruction( $system_instruction )
			->using_temperature( 0.2 );

		$model_preference = trim( (string) $model_preference );

		if ( '' !== $model_preference ) {
			$builder = $builder->using_model_preference( $model_preference );
		}

		$history_messages = self::build_history_messages( $history );

		if ( ! empty( $history_messages ) && method_exists( $builder, 'with_history' ) ) {
			$builder = $builder->with_history( ...$history_messages );
		}

		$answer = $builder->generate_text();

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

		$answer = trim( (string) $answer );

		if ( '' === $answer ) {
			return new WP_Error( 'maca_tjatt_ai_empty', __( 'Empty response from the AI provider.', 'maca-tjatt' ) );
		}

		return $answer;
	}

	/**
	 * @param array<int, array<string, string>> $history Chat history.
	 * @return array<int, object>
	 */
	private static function build_history_messages( $history ) {
		if ( ! is_array( $history ) || empty( $history ) ) {
			return array();
		}

		if ( ! class_exists( 'WordPress\AiClient\Messages\DTO\UserMessage' ) || ! class_exists( 'WordPress\AiClient\Messages\DTO\ModelMessage' ) ) {
			return array();
		}

		$messages = array();

		foreach ( array_slice( $history, -4 ) as $turn ) {
			if ( ! is_array( $turn ) ) {
				continue;
			}

			$role    = isset( $turn['role'] ) ? sanitize_key( (string) $turn['role'] ) : '';
			$content = isset( $turn['content'] ) ? trim( (string) $turn['content'] ) : '';

			if ( '' === $content ) {
				continue;
			}

			if ( 'user' === $role ) {
				$messages[] = new \WordPress\AiClient\Messages\DTO\UserMessage( $content );
				continue;
			}

			if ( 'assistant' === $role ) {
				$messages[] = new \WordPress\AiClient\Messages\DTO\ModelMessage( $content );
			}
		}

		return $messages;
	}
}
