<?php
/**
 * WordPress AI provider.
 *
 * @package Ugcify\AI
 */

namespace Ugcify\AI;

use WP_Error;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class WordPressAIProvider extends AbstractAIProvider {
	/**
	 * Provider slug.
	 *
	 * @var string
	 */
	protected $provider = 'wordpress';

	/**
	 * Analyze hotspot suggestions.
	 *
	 * @param array<string,mixed>             $image_source Image source block info.
	 * @param array<int,array<string,mixed>>  $candidates Candidate products.
	 * @param array<string,mixed>             $context Review context.
	 * @return array<string,mixed>|WP_Error
	 */
	public function analyze_hotspots( array $image_source, array $candidates, array $context = array() ) {
		if ( ! AISettings::is_wordpress_ai_available() ) {
			return new WP_Error( 'wordpress_ai_unavailable', __( 'WordPress AI is not available or enabled.', 'ugcify' ) );
		}

		$image_payload = $this->get_image_payload( $image_source );
		if ( is_wp_error( $image_payload ) ) {
			return $image_payload;
		}

		$prompt = $this->build_instruction_text( $candidates, $context, (int) $this->settings['max_suggestions'] );
		$args   = array(
			'prompt'       => $prompt,
			'image_source' => $image_source,
			'image'        => $image_payload,
			'candidates'   => $candidates,
			'context'      => $context,
		);

		$result = apply_filters( 'ugcify_wordpress_ai_hotspot_response', null, $args );
		if ( null !== $result ) {
			return $this->normalize_response( $result );
		}

		if ( function_exists( 'wp_ai_client_prompt' ) ) {
			try {
				$prompt_builder = wp_ai_client_prompt( $prompt )
					->with_file( $this->get_image_reference( $image_source, $image_payload ), (string) $image_payload['media_type'] )
					->using_temperature( 0.2 );

				if ( function_exists( '\WordPress\AI\get_preferred_vision_models' ) ) {
					$preferred_models = \WordPress\AI\get_preferred_vision_models();
					if ( ! empty( $preferred_models ) ) {
						$prompt_builder = $prompt_builder->using_model_preference( ...$preferred_models );
					}
				}

				if ( ! $prompt_builder->is_supported_for_text_generation() ) {
					return new WP_Error( 'wordpress_ai_vision_unsupported', __( 'WordPress AI does not have a connected provider that supports image analysis.', 'ugcify' ) );
				}

				return $this->normalize_response( $prompt_builder->generate_text() );
			} catch ( \Throwable $throwable ) {
				return new WP_Error( 'wordpress_ai_request_failed', $throwable->getMessage() );
			}
		}

		if ( function_exists( 'wp_ai_generate' ) ) {
			try {
				$result = wp_ai_generate(
					array(
						'prompt'          => $prompt,
						'image'           => $image_payload,
						'response_format' => array( 'type' => 'json_object' ),
					)
				);
				return $this->normalize_response( $result );
			} catch ( \Throwable $throwable ) {
				return new WP_Error( 'wordpress_ai_request_failed', $throwable->getMessage() );
			}
		}

		return new WP_Error( 'wordpress_ai_adapter_missing', __( 'WordPress AI is enabled, but no compatible generation API was found.', 'ugcify' ) );
	}

	/**
	 * Get image reference for the WordPress AI prompt builder.
	 *
	 * @param array<string,mixed>  $image_source Image source block info.
	 * @param array<string,string> $image_payload Image payload.
	 * @return string
	 */
	private function get_image_reference( array $image_source, array $image_payload ): string {
		if ( ! empty( $image_source['path'] ) && is_readable( (string) $image_source['path'] ) ) {
			return (string) $image_source['path'];
		}

		if ( ! empty( $image_payload['url'] ) ) {
			return (string) $image_payload['url'];
		}

		return (string) $image_payload['data'];
	}

	/**
	 * Normalize AI response.
	 *
	 * @param mixed $result AI result.
	 * @return array<string,mixed>|WP_Error
	 */
	private function normalize_response( $result ) {
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		if ( is_array( $result ) && isset( $result['suggestions'] ) ) {
			return $result;
		}

		$text = '';
		if ( is_string( $result ) ) {
			$text = $result;
		} elseif ( is_array( $result ) ) {
			$text = isset( $result['text'] ) ? (string) $result['text'] : wp_json_encode( $result );
		} elseif ( is_object( $result ) ) {
			$text = isset( $result->text ) ? (string) $result->text : wp_json_encode( $result );
		}

		$json = $this->extract_json_object( (string) $text );
		if ( ! is_array( $json ) ) {
			return new WP_Error( 'invalid_provider_json', __( 'WordPress AI did not return valid JSON.', 'ugcify' ) );
		}

		return $json;
	}
}
