<?php
/**
 * Provider Factory
 *
 * Creates and manages AI provider instances.
 *
 * @package Askany
 * @since 1.0.0
 */

namespace Askany\Providers;

/**
 * Factory class for creating AI providers.
 */
class ProviderFactory {
	/**
	 * Get all available providers.
	 *
	 * @return array Array of provider names and display names.
	 */
	public static function get_available_providers(): array {
		return array(
			'openai'     => 'OpenAI',
			'deepseek'   => 'DeepSeek',
			'gemini'     => 'Google Gemini',
			'claude'     => 'Anthropic Claude',
			'grok'       => 'X.AI Grok',
			'openrouter' => 'OpenRouter (100+ Models)',
		);
	}

	/**
	 * Create a provider instance.
	 *
	 * @param string $provider_name Provider name (openai, deepseek, gemini, claude, grok, openrouter).
	 * @param string $api_key API key for the provider.
	 * @param string $api_url Optional custom API URL.
	 * @return AIProviderInterface|null Provider instance or null if invalid.
	 */
	public static function create( string $provider_name, string $api_key, string $api_url = '' ): ?AIProviderInterface {
		switch ( $provider_name ) {
			case 'openai':
				return new OpenAIProvider( $api_key, $api_url );
			case 'deepseek':
				return new DeepSeekProvider( $api_key, $api_url );
			case 'gemini':
				return new GeminiProvider( $api_key, $api_url );
			case 'claude':
				return new ClaudeProvider( $api_key, $api_url );
			case 'grok':
				return new GrokProvider( $api_key, $api_url );
			case 'openrouter':
				return new OpenRouterProvider( $api_key, $api_url );
			default:
				return null;
		}
	}

	/**
	 * Get provider instance from WordPress options.
	 *
	 * @return AIProviderInterface|null Provider instance or null if not configured.
	 */
	public static function create_from_settings(): ?AIProviderInterface {
		$provider_name = get_option( 'askany_api_provider', 'deepseek' );
		
		// Get API key based on provider
		$api_key_option = 'askany_api_key_' . $provider_name;
		$api_key = get_option( $api_key_option, '' );
		
		// Get API URL based on provider
		$api_url_option = 'askany_api_url_' . $provider_name;
		$api_url = get_option( $api_url_option, '' );

		if ( empty( $api_key ) ) {
			return null;
		}

		return self::create( $provider_name, $api_key, $api_url );
	}
}
