<?php
/**
 * Answyr — Anthropic (Claude) provider.
 *
 * complete() uses the WP HTTP API (blocking) — fine for Desk drafts and chat
 * answers, which are single request/response.
 *
 * @package Answyr
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

final class Answyr_Provider_Anthropic extends Answyr_AI_Provider {

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

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

	public function label(): string {
		return __( 'Anthropic (Claude)', 'answyr' );
	}

	public function key_url(): string {
		return 'https://console.anthropic.com/settings/keys';
	}

	public function models(): array {
		return array(
			'claude-opus-4-8'           => 'Claude Opus 4.8 (best quality)',
			'claude-sonnet-4-6'         => 'Claude Sonnet 4.6 (balanced)',
			'claude-haiku-4-5-20251001' => 'Claude Haiku 4.5 (fast/cheap)',
		);
	}

	public function default_model(): string {
		return 'claude-sonnet-4-6';
	}

	public function complete( string $system, array $messages, array $opts ): string {
		$payload = array(
			'model'      => $this->opt( $opts, 'model', $this->default_model() ),
			'max_tokens' => (int) $this->opt( $opts, 'max_tokens', 1500 ),
			'system'     => $system,
			'messages'   => $messages,
		);

		$temperature = $this->opt( $opts, 'temperature', null );
		if ( null !== $temperature ) {
			$payload['temperature'] = (float) $temperature;
		}

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

		if ( is_wp_error( $response ) ) {
			throw new \RuntimeException( esc_html( $response->get_error_message() ) );
		}

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

		if ( 200 !== (int) $code ) {
			$msg = $body['error']['message'] ?? wp_remote_retrieve_response_message( $response );
			throw new \RuntimeException(
				/* translators: 1: HTTP code, 2: error message */
				esc_html( sprintf( __( 'Anthropic API error (%1$d): %2$s', 'answyr' ), $code, $msg ) )
			);
		}

		// content is an array of blocks; concatenate text blocks.
		$text = '';
		foreach ( (array) ( $body['content'] ?? array() ) as $block ) {
			if ( ( $block['type'] ?? '' ) === 'text' ) {
				$text .= $block['text'] ?? '';
			}
		}
		return $text;
	}

	public function test_connection( string $api_key ): bool {
		$response = wp_remote_post(
			self::API_BASE . '/messages',
			array(
				'headers' => array(
					'Content-Type'      => 'application/json',
					'x-api-key'         => $api_key,
					'anthropic-version' => self::API_VER,
				),
				'body'    => wp_json_encode(
					array(
						'model'      => 'claude-haiku-4-5-20251001',
						'max_tokens' => 10,
						'messages'   => array(
							array(
								'role'    => 'user',
								'content' => 'Say "ok".',
							),
						),
					)
				),
				'timeout' => 15,
			)
		);

		return ! is_wp_error( $response ) && 200 === (int) wp_remote_retrieve_response_code( $response );
	}
}
