<?php
/**
 * Basic Forms module AI settings (provider + model).
 *
 * @package BasicForms
 */

namespace BasicForms;

use WP_PowerSuite\AI\ConnectionSettings;
use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

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

final class AiSettings {

	public const MODULE_ID = 'basic-forms';

	/** @var array<string, mixed>|null */
	private static ?array $cache = null;

	/**
	 * @return array<string, string>
	 */
	public static function defaults(): array {
		$conn     = ConnectionSettings::get();
		$provider = ConnectionSettings::sanitizeProvider( (string) ( $conn['provider'] ?? 'openai' ) );

		return [
			'provider' => $provider,
			'model'    => FormAiModels::getDefault( $provider ),
		];
	}

	/**
	 * @return array<string, string>
	 */
	public static function get(): array {
		if ( self::$cache !== null ) {
			return self::$cache;
		}

		$saved  = OptionStoreModuleSettingsRepository::forModule( self::MODULE_ID )->all( [] );
		$merged = is_array( $saved ) ? array_merge( self::defaults(), $saved ) : self::defaults();
		$merged['provider'] = self::sanitizeProvider( (string) ( $merged['provider'] ?? 'openai' ) );
		$merged['model']    = FormAiModels::sanitize( (string) ( $merged['model'] ?? '' ), $merged['provider'] );

		self::$cache = $merged;

		return self::$cache;
	}

	public static function flushCache(): void {
		self::$cache = null;
	}

	/**
	 * Whether the AI Form Builder assistant is enabled. Defaults to enabled.
	 */
	public static function isEnabled(): bool {
		$settings = self::get();
		if ( ! array_key_exists( 'ai_enabled', $settings ) ) {
			return true;
		}

		$value = $settings['ai_enabled'];
		if ( is_bool( $value ) ) {
			return $value;
		}

		return ! in_array( (string) $value, [ '0', 'false', 'no', '' ], true );
	}

	/**
	 * @return array<string, mixed>
	 */
	public static function getPublic(): array {
		$settings = self::get();
		$provider = (string) ( $settings['provider'] ?? 'openai' );

		return [
			'provider'    => $provider,
			'model'       => (string) ( $settings['model'] ?? FormAiModels::getDefault( $provider ) ),
			'has_api_key' => ConnectionSettings::hasApiKey( $provider ),
			'providers'   => ConnectionSettings::providerLabels(),
		];
	}

	public static function sanitizeProvider( string $provider ): string {
		return ConnectionSettings::sanitizeProvider( $provider );
	}

	public static function hasApiKey( ?string $provider = null ): bool {
		$settings = self::get();
		$provider = self::sanitizeProvider( $provider ?? (string) ( $settings['provider'] ?? 'openai' ) );

		return ConnectionSettings::hasApiKey( $provider );
	}

	/**
	 * @param array<string, mixed> $settings
	 * @param array<string, mixed> $existing
	 * @return array<string, string>
	 */
	public static function normalize( array $settings, array $existing = [] ): array {
		$merged   = array_merge( self::defaults(), is_array( $existing ) ? $existing : [], $settings );
		$provider = self::sanitizeProvider( (string) ( $settings['provider'] ?? $merged['provider'] ?? 'openai' ) );

		$enabled_raw = $settings['ai_enabled'] ?? $merged['ai_enabled'] ?? true;
		$enabled     = ! in_array(
			is_bool( $enabled_raw ) ? $enabled_raw : (string) $enabled_raw,
			[ false, '0', 'false', 'no', '' ],
			true
		);

		$normalized = [
			'provider'   => $provider,
			'model'      => FormAiModels::sanitize( (string) ( $settings['model'] ?? $merged['model'] ?? '' ), $provider ),
			'ai_enabled' => $enabled,
		];

		return FeatureGate::preservePremiumSettingsOnSave( $normalized, $existing );
	}
}
