<?php
/**
 * Shared helpers for WPStack AI ALT Genius.
 *
 * @package WPStack_AI_ALT_Genius
 */

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

/**
 * Utility methods used across the plugin.
 */
class Aialtg_Helpers {

	/**
	 * Keywords used to detect vision-capable models (model ID substring match).
	 *
	 * @return string[]
	 */
	public static function vision_keywords() {
		return array(
			'vl-', 'vl_', 'vision', 'vila', 'vlm', '-vl', 'florence', 'pixtral', 'qwen-vl',
			'gemini', 'gemma-3', 'gemma-4', 'gpt-4o', 'gpt-4-turbo', 'gpt-4-vision',
			'claude-3', 'claude-4', 'o3', 'o4', 'fuyu', 'kosmos', 'deplot', 'neva',
			'nvclip', 'cosmos-reason', 'multimodal', 'parse', 'phi-4', 'minimax-m3',
		);
	}

	/**
	 * Read a yes/no option stored as '1' or '0'.
	 *
	 * @param array  $options Settings array.
	 * @param string $key     Option key.
	 * @param bool   $default Default when key is missing.
	 * @return bool
	 */
	public static function is_enabled( $options, $key, $default = true ) {
		if ( ! isset( $options[ $key ] ) ) {
			return $default;
		}
		return '1' === $options[ $key ];
	}

	/**
	 * Non-empty NVIDIA API keys from settings.
	 *
	 * @param array $options Settings array.
	 * @return string[]
	 */
	public static function get_nvidia_keys( $options ) {
		$keys = isset( $options['nvidia_api_keys'] ) ? $options['nvidia_api_keys'] : array();
		if ( ! is_array( $keys ) ) {
			return array();
		}
		return array_values( array_filter( $keys ) );
	}

	/**
	 * Resolve which API key to use for a request.
	 *
	 * @param array       $options   Settings array.
	 * @param string      $override  Explicit key (cron per-slot assignment).
	 * @param int|null    $key_index Fixed NVIDIA pool index.
	 * @return string
	 */
	public static function resolve_api_key( $options, $override = '', $key_index = null ) {
		if ( ! empty( $override ) ) {
			return $override;
		}

		$provider = isset( $options['provider'] ) ? $options['provider'] : 'openrouter';

		if ( 'nvidia' === $provider ) {
			$nvidia_keys = self::get_nvidia_keys( $options );
			if ( ! empty( $nvidia_keys ) ) {
				if ( null !== $key_index && isset( $nvidia_keys[ $key_index ] ) ) {
					return $nvidia_keys[ $key_index ];
				}
				$idx = (int) get_transient( 'aialtg_nvidia_key_index' );
				if ( $idx < 0 || $idx >= count( $nvidia_keys ) ) {
					$idx = 0;
				}
				set_transient( 'aialtg_nvidia_key_index', $idx + 1, HOUR_IN_SECONDS );
				return $nvidia_keys[ $idx ];
			}
		}

		return isset( $options['api_key'] ) ? $options['api_key'] : '';
	}

	/**
	 * Check whether a model supports image input.
	 *
	 * @param string $model    Model ID.
	 * @param string $provider Provider slug.
	 * @return bool
	 */
	public static function model_supports_vision( $model, $provider ) {
		$model_lower = strtolower( $model );
		foreach ( self::vision_keywords() as $keyword ) {
			if ( false !== strpos( $model_lower, $keyword ) ) {
				return true;
			}
		}

		$cache_key = 'aialtg_models_' . $provider;
		$cached    = get_transient( $cache_key );
		if ( is_array( $cached ) ) {
			foreach ( $cached as $cached_model ) {
				if ( isset( $cached_model['id'], $cached_model['architecture']['input_modalities'] )
					&& $cached_model['id'] === $model
					&& in_array( 'image', $cached_model['architecture']['input_modalities'], true ) ) {
					return true;
				}
			}
		}

		return false;
	}

	/**
	 * Preserve a secret field value when the settings form leaves it blank.
	 *
	 * @param string $submitted Submitted value.
	 * @param string $existing  Previously stored value.
	 * @return string
	 */
	public static function preserve_secret_field( $submitted, $existing ) {
		$submitted = sanitize_text_field( $submitted );
		if ( '' !== $submitted ) {
			return $submitted;
		}
		return is_string( $existing ) ? $existing : '';
	}
}
