<?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;
}

require_once __DIR__ . '/FeatureGate.php';

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 {
		$provider = 'openai';
		if ( class_exists( ConnectionSettings::class ) ) {
			$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' => class_exists( ConnectionSettings::class ) && ConnectionSettings::hasApiKey( $provider ),
			'providers'   => class_exists( ConnectionSettings::class ) ? ConnectionSettings::providerLabels() : [],
		];
	}

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

		$provider = sanitize_key( $provider );

		return $provider !== '' ? $provider : 'openai';
	}

	public static function hasApiKey( ?string $provider = null ): bool {
		if ( ! class_exists( ConnectionSettings::class ) ) {
			return false;
		}

		$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 );
	}
}
