<?php
/**
 * Anthropic provider.
 *
 * @package CatalogPilot\AiStudio
 */

namespace CatalogPilot\AiStudio\Providers;

defined( 'ABSPATH' ) || exit;

final class Anthropic_Provider extends Provider {

	const API_BASE        = 'https://api.anthropic.com/v1';
	const ANTHROPIC_VERSION = '2023-06-01';

	public function id() {
		return 'anthropic';
	}

	public function complete( $system, $user ) {
		if ( '' === $this->api_key ) {
			return new \WP_Error( 'cpais_missing_key', __( 'Anthropic API key is not configured.', 'catalogpilot-ai-studio-for-woocommerce' ) );
		}

		$body = array(
			'model'      => $this->model,
			'max_tokens' => 4096,
			'system'     => $system . "\n\nRespond with a single JSON object only. No prose, no code fences.",
			'messages'   => array(
				array( 'role' => 'user', 'content' => $user ),
			),
		);

		$data = $this->request(
			self::API_BASE . '/messages',
			array(
				'headers' => array(
					'x-api-key'         => $this->api_key,
					'anthropic-version' => self::ANTHROPIC_VERSION,
					'Content-Type'      => 'application/json',
				),
				'body' => wp_json_encode( $body ),
			)
		);

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

		$text = '';
		if ( isset( $data['content'] ) && is_array( $data['content'] ) ) {
			foreach ( $data['content'] as $block ) {
				if ( 'text' === ( $block['type'] ?? '' ) ) {
					$text .= $block['text'] ?? '';
				}
			}
		}

		return array(
			'text'  => $text,
			'usage' => array(
				'input_tokens'  => $data['usage']['input_tokens'] ?? 0,
				'output_tokens' => $data['usage']['output_tokens'] ?? 0,
			),
		);
	}

	public function complete_vision( $system, $user, array $image_urls ) {
		if ( '' === $this->api_key ) {
			return new \WP_Error( 'cpais_missing_key', __( 'Anthropic API key is not configured.', 'catalogpilot-ai-studio-for-woocommerce' ) );
		}

		$content_blocks = array();
		foreach ( $image_urls as $url ) {
			$fetched = wp_remote_get( $url, array( 'timeout' => 30 ) );
			if ( is_wp_error( $fetched ) ) {
				return $fetched;
			}
			$bytes = wp_remote_retrieve_body( $fetched );
			$mime  = wp_remote_retrieve_header( $fetched, 'content-type' ) ?: 'image/jpeg';
			$mime  = strtolower( trim( explode( ';', $mime )[0] ) );
			$content_blocks[] = array(
				'type'   => 'image',
				'source' => array(
					'type'       => 'base64',
					'media_type' => $mime,
					'data'       => base64_encode( $bytes ), // phpcs:ignore
				),
			);
		}
		$content_blocks[] = array( 'type' => 'text', 'text' => (string) $user );

		$body = array(
			'model'      => $this->model,
			'max_tokens' => 300,
			'system'     => $system,
			'messages'   => array( array( 'role' => 'user', 'content' => $content_blocks ) ),
		);

		$data = $this->request(
			self::API_BASE . '/messages',
			array(
				'headers' => array(
					'x-api-key'         => $this->api_key,
					'anthropic-version' => self::ANTHROPIC_VERSION,
					'Content-Type'      => 'application/json',
				),
				'body'    => wp_json_encode( $body ),
			)
		);
		if ( is_wp_error( $data ) ) {
			return $data;
		}

		$text = '';
		foreach ( (array) ( $data['content'] ?? array() ) as $block ) {
			if ( 'text' === ( $block['type'] ?? '' ) ) {
				$text .= $block['text'] ?? '';
			}
		}
		return array(
			'text'  => $text,
			'usage' => array(
				'input_tokens'  => $data['usage']['input_tokens']  ?? 0,
				'output_tokens' => $data['usage']['output_tokens'] ?? 0,
			),
		);
	}

	public function test_connection() {
		if ( '' === $this->api_key ) {
			return new \WP_Error( 'cpais_missing_key', __( 'Anthropic API key is required.', 'catalogpilot-ai-studio-for-woocommerce' ) );
		}

		$body = array(
			'model'      => $this->model,
			'max_tokens' => 8,
			'messages'   => array( array( 'role' => 'user', 'content' => 'ping' ) ),
		);

		$response = wp_remote_post(
			self::API_BASE . '/messages',
			array(
				'timeout' => 20,
				'headers' => array(
					'x-api-key'         => $this->api_key,
					'anthropic-version' => self::ANTHROPIC_VERSION,
					'Content-Type'      => 'application/json',
				),
				'body' => wp_json_encode( $body ),
			)
		);

		if ( is_wp_error( $response ) ) {
			return $response;
		}
		$code = wp_remote_retrieve_response_code( $response );
		if ( 200 !== $code ) {
			$data = json_decode( wp_remote_retrieve_body( $response ), true );
			$msg  = $data['error']['message'] ?? __( 'Authentication failed.', 'catalogpilot-ai-studio-for-woocommerce' );
			return new \WP_Error( 'cpais_auth_failed', $msg, array( 'status' => $code ) );
		}
		return true;
	}
}
