<?php
/**
 * Text model registry for Basic Forms AI generation.
 *
 * @package BasicForms
 */

namespace BasicForms;

use WP_PowerSuite\AI\OpenRouterModels;

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

final class FormAiModels {

	/**
	 * Retired model IDs mapped to the closest current replacement.
	 *
	 * @var array<string, string>
	 */
	private const RETIRED_MAP = [
		'gemini-2.0-flash'           => 'gemini-2.5-flash',
		'gemini-2.0-flash-lite'      => 'gemini-2.5-flash-lite',
		'gemini-1.5-pro'             => 'gemini-2.5-pro',
		'gemini-1.5-flash'           => 'gemini-2.5-flash',
		'claude-3-5-haiku-latest'    => 'claude-haiku-4-5-20251001',
		'claude-3-5-sonnet-latest'   => 'claude-sonnet-4-6',
		'claude-3-haiku-20240307'    => 'claude-haiku-4-5-20251001',
		'grok-2-latest'              => 'grok-4.3',
		'anthropic/claude-3.5-haiku' => 'anthropic/claude-haiku-4.5',
		'google/gemini-2.0-flash-001' => 'google/gemini-2.5-flash',
	];

	/**
	 * @return array<string, array{label: string, models: array<string, string>}>
	 */
	public static function getGroups( string $provider ): array {
		$provider = AiSettings::sanitizeProvider( $provider );

		$groups = match ( $provider ) {
			'gemini'     => self::geminiGroups(),
			'claude'     => self::claudeGroups(),
			'openrouter' => self::openRouterGroups(),
			'deepseek'   => self::deepseekGroups(),
			'grok'       => self::grokGroups(),
			default      => self::openAiGroups(),
		};

		/**
		 * Filter grouped text models for Basic Forms AI generation.
		 *
		 * @param array<string, array{label: string, models: array<string, string>}> $groups
		 * @param string                                                            $provider
		 */
		return apply_filters( 'wpps_basic_forms_ai_model_groups', $groups, $provider );
	}

	/**
	 * @return array<string, string>
	 */
	public static function getList( string $provider ): array {
		$list = [];
		foreach ( self::getGroups( $provider ) as $group ) {
			if ( ! isset( $group['models'] ) || ! is_array( $group['models'] ) ) {
				continue;
			}
			foreach ( $group['models'] as $id => $label ) {
				$list[ (string) $id ] = (string) $label;
			}
		}

		return $list;
	}

	public static function getDefault( string $provider ): string {
		return match ( AiSettings::sanitizeProvider( $provider ) ) {
			'gemini'     => 'gemini-2.5-flash',
			'claude'     => 'claude-haiku-4-5-20251001',
			'openrouter' => 'openrouter/free',
			'deepseek'   => 'deepseek-chat',
			'grok'       => 'grok-4.3',
			default      => 'gpt-4o-mini',
		};
	}

	public static function sanitize( string $model, string $provider ): string {
		$provider = AiSettings::sanitizeProvider( $provider );
		$model    = trim( sanitize_text_field( $model ) );

		if ( $model === '' ) {
			return self::getDefault( $provider );
		}

		if ( isset( self::RETIRED_MAP[ $model ] ) ) {
			$model = self::RETIRED_MAP[ $model ];
		}

		$allowed = array_keys( self::getList( $provider ) );
		if ( in_array( $model, $allowed, true ) ) {
			return $model;
		}

		if ( $provider === 'openrouter' && self::isAllowedOpenRouterModel( $model ) ) {
			return $model;
		}

		return self::getDefault( $provider );
	}

	private static function isAllowedOpenRouterModel( string $model ): bool {
		if ( $model === 'openrouter/free' || str_ends_with( $model, ':free' ) ) {
			return (bool) preg_match( '/^[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._:-]*$/i', $model );
		}

		return false;
	}

	public static function getSettingsHint( string $provider ): string {
		return match ( AiSettings::sanitizeProvider( $provider ) ) {
			'gemini'     => __( 'Gemini 2.5 Flash is the recommended default for fast form generation.', 'wppowersuite-lite' ),
			'claude'     => __( 'Claude Haiku 4.5 is fast and cost-effective. Use Sonnet 4.6 for complex multi-section forms.', 'wppowersuite-lite' ),
			'openrouter' => __( 'OpenRouter supports free models with the same API key. Use the Free group for zero-cost options, or pick a paid model from Recommended.', 'wppowersuite-lite' ),
			'deepseek'   => __( 'DeepSeek Chat is the recommended default for form generation.', 'wppowersuite-lite' ),
			'grok'       => __( 'Grok 4.3 is the recommended default for Grok.', 'wppowersuite-lite' ),
			default      => __( 'GPT-4o mini is the recommended default. Use GPT-5.5 or GPT-4.1 for large or complex forms.', 'wppowersuite-lite' ),
		};
	}

	/**
	 * @return array<string, array{label: string, models: array<string, string>}>
	 */
	private static function openAiGroups(): array {
		return [
			'recommended' => [
				'label'  => __( 'Recommended', 'wppowersuite-lite' ),
				'models' => [
					'gpt-4o-mini'   => __( 'GPT-4o mini — recommended default', 'wppowersuite-lite' ),
					'gpt-5.4-mini'  => __( 'GPT-5.4 mini — fast and capable', 'wppowersuite-lite' ),
					'gpt-5.5-mini'  => __( 'GPT-5.5 mini — strong quality at lower cost', 'wppowersuite-lite' ),
					'gpt-4o'        => __( 'GPT-4o — complex forms', 'wppowersuite-lite' ),
					'gpt-4.1-mini'  => __( 'GPT-4.1 mini — fast', 'wppowersuite-lite' ),
					'gpt-4.1'       => __( 'GPT-4.1 — high quality', 'wppowersuite-lite' ),
					'gpt-5.4'       => __( 'GPT-5.4 — advanced reasoning', 'wppowersuite-lite' ),
					'gpt-5.5'       => __( 'GPT-5.5 — highest quality', 'wppowersuite-lite' ),
				],
			],
		];
	}

	/**
	 * @return array<string, array{label: string, models: array<string, string>}>
	 */
	private static function geminiGroups(): array {
		return [
			'recommended' => [
				'label'  => __( 'Recommended', 'wppowersuite-lite' ),
				'models' => [
					'gemini-2.5-flash'      => __( 'Gemini 2.5 Flash — recommended default', 'wppowersuite-lite' ),
					'gemini-2.5-flash-lite' => __( 'Gemini 2.5 Flash Lite — lowest cost', 'wppowersuite-lite' ),
					'gemini-2.5-pro'        => __( 'Gemini 2.5 Pro — complex forms', 'wppowersuite-lite' ),
					'gemini-3.5-flash'      => __( 'Gemini 3.5 Flash — latest generation', 'wppowersuite-lite' ),
				],
			],
		];
	}

	/**
	 * @return array<string, array{label: string, models: array<string, string>}>
	 */
	private static function claudeGroups(): array {
		return [
			'recommended' => [
				'label'  => __( 'Recommended', 'wppowersuite-lite' ),
				'models' => [
					'claude-haiku-4-5-20251001' => __( 'Claude Haiku 4.5 — recommended default', 'wppowersuite-lite' ),
					'claude-sonnet-4-6'         => __( 'Claude Sonnet 4.6 — complex forms', 'wppowersuite-lite' ),
					'claude-opus-4-8'           => __( 'Claude Opus 4.8 — highest quality', 'wppowersuite-lite' ),
				],
			],
		];
	}

	private static function openRouterGroups(): array {
		$free_models = class_exists( OpenRouterModels::class ) ? OpenRouterModels::getFreeModels() : [];
		if ( ! isset( $free_models['openrouter/free'] ) ) {
			$free_models = array_merge(
				[
					'openrouter/free' => __( 'Free Models Router — auto-selects a free model', 'wppowersuite-lite' ),
				],
				$free_models
			);
		}

		return [
			'free' => [
				'label'  => __( 'Free', 'wppowersuite-lite' ),
				'models' => $free_models,
			],
			'recommended' => [
				'label'  => __( 'Recommended (paid)', 'wppowersuite-lite' ),
				'models' => [
					'openai/gpt-4o-mini'          => __( 'GPT-4o mini — fast default', 'wppowersuite-lite' ),
					'openai/gpt-5-mini'           => __( 'GPT-5 mini — fast and capable', 'wppowersuite-lite' ),
					'openai/gpt-4o'               => __( 'GPT-4o — complex forms', 'wppowersuite-lite' ),
					'anthropic/claude-haiku-4.5'  => __( 'Claude Haiku 4.5 — fast', 'wppowersuite-lite' ),
					'google/gemini-2.5-flash'     => __( 'Gemini 2.5 Flash — fast', 'wppowersuite-lite' ),
				],
			],
		];
	}

	private static function deepseekGroups(): array {
		return [
			'recommended' => [
				'label'  => __( 'Recommended', 'wppowersuite-lite' ),
				'models' => [
					'deepseek-chat'     => __( 'DeepSeek Chat — recommended default', 'wppowersuite-lite' ),
					'deepseek-reasoner' => __( 'DeepSeek Reasoner — complex forms', 'wppowersuite-lite' ),
				],
			],
		];
	}

	private static function grokGroups(): array {
		return [
			'recommended' => [
				'label'  => __( 'Recommended', 'wppowersuite-lite' ),
				'models' => [
					'grok-4.3' => __( 'Grok 4.3 — recommended default', 'wppowersuite-lite' ),
				],
			],
		];
	}
}
