<?php
/**
 * AI provider registry.
 *
 * @package AIAltTextGenerator
 * @since 1.6.0
 */

namespace AIAltTextGenerator;

use AIAltTextGenerator\Providers\ClaudeProvider;
use AIAltTextGenerator\Providers\GeminiProvider;
use AIAltTextGenerator\Providers\OpenAIProvider;
use AIAltTextGenerator\Providers\ProviderInterface;

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

/**
 * @since 1.6.0
 */
class ProviderRegistry {

	/** @return array<string, ProviderInterface> */
	public static function all(): array {
		$map = [
			'openai' => new OpenAIProvider(),
		];
		if ( class_exists( GeminiProvider::class, false ) ) {
			$map['gemini'] = new GeminiProvider();
		}
		if ( class_exists( ClaudeProvider::class, false ) ) {
			$map['claude'] = new ClaudeProvider();
		}

		return $map;
	}

	public static function get( ?string $provider_id = null ): ProviderInterface {
		$settings    = Settings::get();
		$provider_id = sanitize_key( $provider_id ?? (string) ( $settings['provider'] ?? 'openai' ) );

		$map = self::all();
		if ( isset( $map[ $provider_id ] ) ) {
			$provider = $map[ $provider_id ];
		} else {
			$provider = $map['openai'];
		}

		/**
		 * Filter the active AI alt text provider instance.
		 *
		 * @param ProviderInterface    $provider    Provider instance.
		 * @param string               $provider_id Selected provider ID.
		 * @param array<string, mixed> $settings    Module settings.
		 */
		$filtered = apply_filters( 'wpps_ai_alt_text_provider', $provider, $provider_id, $settings );

		return $filtered instanceof ProviderInterface ? $filtered : $provider;
	}

	/** @return array<string, string> */
	public static function labels(): array {
		$labels = [];
		foreach ( self::all() as $id => $provider ) {
			$labels[ $id ] = $provider->getLabel();
		}
		return $labels;
	}
}
