<?php
/**
 * Lightweight AI provider connection tests for site-wide settings.
 *
 * @package WP_PowerSuite\AI
 */

namespace WP_PowerSuite\AI;

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

final class ConnectionTester {

	public static function test( string $provider, string $api_key = '' ): bool|\WP_Error {
		$provider = ConnectionSettings::sanitizeProvider( $provider );
		$key      = trim( $api_key );
		if ( $key === '' ) {
			$key = ConnectionSettings::getApiKey( null, $provider );
		}

		if ( $key === '' ) {
			return new \WP_Error(
				'missing_api_key',
				__( 'API key is not configured.', 'wp-powersuite' )
			);
		}

		return match ( ProviderRegistry::apiFamily( $provider ) ) {
			'gemini'            => self::testGemini( $key ),
			'claude'            => self::testClaude( $key ),
			'openai_compatible' => self::testOpenAiCompatible( $provider, $key ),
			default             => self::testOpenAi( $key ),
		};
	}

	private static function testOpenAi( string $api_key ): bool|\WP_Error {
		return OpenAiCompatibleClient::testConnection( 'https://api.openai.com/v1', $api_key );
	}

	private static function testOpenAiCompatible( string $provider, string $api_key ): bool|\WP_Error {
		$extra_headers = $provider === 'openrouter' ? OpenAiCompatibleClient::openRouterHeaders() : [];

		return OpenAiCompatibleClient::testConnection(
			ProviderRegistry::baseUrl( $provider ),
			$api_key,
			$extra_headers
		);
	}

	private static function testGemini( string $api_key ): bool|\WP_Error {
		$response = wp_remote_get(
			'https://generativelanguage.googleapis.com/v1beta/models',
			[
				'timeout' => 20,
				'headers' => [ 'x-goog-api-key' => $api_key ],
			]
		);

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

		if ( wp_remote_retrieve_response_code( $response ) !== 200 ) {
			return new \WP_Error( 'api_error', __( 'Gemini API connection failed.', 'wp-powersuite' ) );
		}

		return true;
	}

	private static function testClaude( string $api_key ): bool|\WP_Error {
		$response = wp_remote_get(
			'https://api.anthropic.com/v1/models',
			[
				'timeout' => 20,
				'headers' => [
					'x-api-key'         => $api_key,
					'anthropic-version' => '2023-06-01',
				],
			]
		);

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

		if ( wp_remote_retrieve_response_code( $response ) !== 200 ) {
			return new \WP_Error( 'api_error', __( 'Claude API connection failed.', 'wp-powersuite' ) );
		}

		return true;
	}
}
