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

namespace Ugcify\AI;

use WP_Error;

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

class AnthropicProvider extends AbstractAIProvider {
	private const API_URL = 'https://api.anthropic.com/v1/messages';

	/**
	 * Provider slug.
	 *
	 * @var string
	 */
	protected $provider = 'anthropic';

	/**
	 * 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() ) {
		$api_key = $this->get_api_key();
		if ( '' === $api_key ) {
			return new WP_Error( 'missing_api_key', __( 'Anthropic API key is missing.', 'ugcify' ) );
		}

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

		$content = array(
			array(
				'type' => 'text',
				'text' => $this->build_instruction_text( $candidates, $context, (int) $this->settings['max_suggestions'] ),
			),
			array(
				'type' => 'text',
				'text' => 'UGC image to analyze:',
			),
		);

		if ( ! empty( $image_payload['data'] ) ) {
			$content[] = array(
				'type'   => 'image',
				'source' => array(
					'type'       => 'base64',
					'media_type' => (string) $image_payload['media_type'],
					'data'       => (string) $image_payload['data'],
				),
			);
		} else {
			$content[] = array(
				'type'   => 'image',
				'source' => array(
					'type' => 'url',
					'url'  => (string) $image_payload['url'],
				),
			);
		}

		$response = wp_remote_post(
			self::API_URL,
			array(
				'timeout' => 60,
				'headers' => array(
					'content-type'      => 'application/json',
					'x-api-key'         => $api_key,
					'anthropic-version' => '2023-06-01',
				),
				'body'    => wp_json_encode(
					array(
						'model'      => $this->get_model(),
						'max_tokens' => 1800,
						'messages'   => array(
							array(
								'role'    => 'user',
								'content' => $content,
							),
						),
					)
				),
			)
		);

		if ( is_wp_error( $response ) ) {
			return new WP_Error( 'provider_request_failed', $response->get_error_message() );
		}

		$status = (int) wp_remote_retrieve_response_code( $response );
		if ( $status < 200 || $status >= 300 ) {
			return new WP_Error( 'provider_http_error', __( 'Anthropic request failed.', 'ugcify' ) );
		}

		$decoded = json_decode( (string) wp_remote_retrieve_body( $response ), true );
		if ( ! is_array( $decoded ) || empty( $decoded['content'] ) || ! is_array( $decoded['content'] ) ) {
			return new WP_Error( 'invalid_provider_response', __( 'Invalid Anthropic response.', 'ugcify' ) );
		}

		$text = '';
		foreach ( $decoded['content'] as $part ) {
			if ( is_array( $part ) && isset( $part['type'], $part['text'] ) && 'text' === $part['type'] ) {
				$text .= (string) $part['text'];
			}
		}

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

		return $json;
	}
}
