<?php

namespace WeDevs\Wpuf\Pro\AI_Review\Providers;

/**
 * Anthropic AI Provider
 *
 * Handles API calls to Anthropic's Claude AI services
 *
 * @since 4.2.9
 */
class Anthropic_Provider extends Abstract_Provider {

	/**
	 * Anthropic API version
	 *
	 * @var string
	 */
	private $api_version = '2023-06-01';

	/**
	 * Make API call to Anthropic
	 *
	 * @since 4.2.9
	 * @param string $endpoint API endpoint
	 * @param string $api_key  API key
	 * @param string $model    Model to use
	 * @param string $prompt   Review prompt
	 * @return string API response
	 * @throws \Exception
	 */
	public function make_api_call( $endpoint, $api_key, $model, $prompt ) {
		$headers = [
			'x-api-key'          => $api_key,
			'Content-Type'       => 'application/json',
			'anthropic-version'  => $this->api_version,
		];

		$args = [
			'headers' => $headers,
			'body'    => json_encode( $this->build_request_body( $prompt ) ),
		];

		$response = $this->make_request( $endpoint, $args );

		$body = wp_remote_retrieve_body( $response );

		return $this->parse_response( $body );
	}

	/**
	 * Validate Anthropic API key format
	 *
	 * Anthropic API keys start with 'sk-ant-' and are typically longer
	 *
	 * @since 4.2.9
	 * @param string $api_key API key to validate
	 * @return bool True if valid format
	 */
	public function validate_api_key( $api_key ) {
		// Anthropic API keys start with 'sk-ant-'
		return ! empty( $api_key ) && preg_match( '/^sk-ant-[a-zA-Z0-9\-]{40,}$/', $api_key );
	}

	/**
	 * Get request headers for Anthropic API
	 *
	 * @since 4.2.9
	 * @return array Request headers
	 */
	protected function get_request_headers() {
		return [
			'x-api-key'          => $this->api_key,
			'Content-Type'       => 'application/json',
			'anthropic-version'  => $this->api_version,
		];
	}

	/**
	 * Parse Anthropic API response
	 *
	 * @since 4.2.9
	 * @param string $response_body Response body
	 * @return string Parsed response content
	 * @throws \Exception
	 */
	protected function parse_response( $response_body ) {
		$decoded = json_decode( $response_body, true );

		if ( isset( $decoded['content'][0]['text'] ) ) {
			return $decoded['content'][0]['text'];
		}

		throw new \Exception( 'Invalid Anthropic API response' );
	}

	/**
	 * Build request body for Anthropic API
	 *
	 * @since 4.2.9
	 * @param string $prompt Review prompt
	 * @return array Request body
	 */
	protected function build_request_body( $prompt ) {
		return [
			'model'      => $this->model,
			'max_tokens' => $this->max_tokens,
			'messages'   => [
				[
					'role'    => 'user',
					'content' => $prompt,
				],
			],
		];
	}
}
