<?php
/**
 * Gemini/Claude rewrite HTTP clients — Pro overlay only.
 *
 * Secure design (rafter-secure-design / auth):
 * - Identity: generation already authorized by GenerationService.
 * - AuthZ: This file is absent from the wordpress.org Lite zip. Lite rewrite
 *   uses OpenAI only. Overlay + license unlocks these providers.
 * - Egress: admin-configured API keys only; no user-supplied URLs.
 *
 * @package AIAltTextGenerator
 * @since 2.5.3
 */

namespace AIAltTextGenerator;

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

/**
 * Premium-provider rewrite requests. Not loaded in Lite.
 *
 * @since 2.5.3
 */
final class PremiumAltRewriter {

	public static function requestGemini( string $api_key, string $model, string $user_prompt, int $timeout ): string|\WP_Error {
		$url = sprintf(
			'https://generativelanguage.googleapis.com/v1beta/models/%s:generateContent',
			rawurlencode( $model )
		);

		$response = wp_remote_post(
			$url,
			[
				'timeout' => $timeout,
				'headers' => [
					'Content-Type'   => 'application/json',
					'x-goog-api-key' => $api_key,
				],
				'body'    => wp_json_encode(
					[
						'contents' => [
							[
								'parts' => [
									[
										'text' => 'Rewrite image alt text. Return only the rewritten alt text with no quotes or commentary.' . "\n\n" . $user_prompt,
									],
								],
							],
						],
					]
				),
			]
		);

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

		$code = (int) wp_remote_retrieve_response_code( $response );
		$data = json_decode( (string) wp_remote_retrieve_body( $response ), true );
		if ( $code < 200 || $code >= 300 || ! is_array( $data ) ) {
			$message = is_array( $data ) ? (string) ( $data['error']['message'] ?? '' ) : '';

			return new \WP_Error( 'rewrite_failed', $message !== '' ? $message : __( 'Alt text rewrite request failed.', 'wp-powersuite' ), [ 'status' => $code ] );
		}

		return trim( (string) ( $data['candidates'][0]['content']['parts'][0]['text'] ?? '' ) );
	}

	public static function requestClaude( string $api_key, string $model, string $user_prompt, int $timeout ): string|\WP_Error {
		$response = wp_remote_post(
			'https://api.anthropic.com/v1/messages',
			[
				'timeout' => $timeout,
				'headers' => [
					'x-api-key'         => $api_key,
					'anthropic-version' => '2023-06-01',
					'content-type'      => 'application/json',
				],
				'body'    => wp_json_encode(
					[
						'model'      => $model,
						'max_tokens' => 200,
						'messages'   => [
							[
								'role'    => 'user',
								'content' => 'Rewrite image alt text. Return only the rewritten alt text with no quotes or commentary.' . "\n\n" . $user_prompt,
							],
						],
					]
				),
			]
		);

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

		$code = (int) wp_remote_retrieve_response_code( $response );
		$data = json_decode( (string) wp_remote_retrieve_body( $response ), true );
		if ( $code < 200 || $code >= 300 || ! is_array( $data ) ) {
			$message = is_array( $data ) ? (string) ( $data['error']['message'] ?? '' ) : '';

			return new \WP_Error( 'rewrite_failed', $message !== '' ? $message : __( 'Alt text rewrite request failed.', 'wp-powersuite' ), [ 'status' => $code ] );
		}

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

		return trim( $content );
	}
}
