<?php

declare(strict_types=1);

namespace FormConnector\Integration\AI;

use WP_Error;

/**
 * AI Mapper
 *
 * Orchestrates AI-powered field mapping suggestions. Sends form field
 * metadata and CareHQ target fields to the FormConnector backend server
 * which proxies the AI request. This allows the server to approve,
 * rate-limit, and audit AI usage per license.
 *
 * Privacy: only field metadata (id, label, type, option labels) is sent
 * to the backend. No submission data or PII is transmitted.
 */
class AIMapper {

	/**
	 * Option key for enabled toggle (local setting)
	 */
	public const OPTION_ENABLED = 'fc_ai_enabled';

	/**
	 * Cache key prefix for transient-based suggestion caching
	 */
	private const CACHE_PREFIX   = 'fc_ai_suggest_';
	private const CACHE_DURATION = 86400; // 24 hours

	/**
	 * Check whether AI mapping is enabled.
	 */
	public static function is_available(): bool {
		return (bool) get_option(self::OPTION_ENABLED, false);
	}

	/**
	 * Get AI settings for the admin UI.
	 */
	public static function get_settings(): array {
		return [
			'enabled' => (bool) get_option(self::OPTION_ENABLED, false),
		];
	}

	/**
	 * Save AI settings from admin UI.
	 */
	public static function save_settings(array $data): array {
		if (isset($data['enabled'])) {
			update_option(self::OPTION_ENABLED, (bool) $data['enabled']);
		}

		return [
			'success' => true,
			'message' => __('AI settings saved.', 'form-connector'),
			'data'    => self::get_settings(),
		];
	}

	/**
	 * Generate field mapping suggestions for a form.
	 *
	 * Sends form field metadata to the FormConnector backend server which
	 * handles AI inference, rate limiting, and approval.
	 *
	 * @param array $form_fields   Form field descriptors from the form adapter
	 * @param array $carehq_fields CareHQ field key => label pairs
	 * @return array|WP_Error Suggestions array or error
	 */
	public static function suggest(array $form_fields, array $carehq_fields): array|WP_Error {
		if (!self::is_available()) {
			return new WP_Error('ai_not_enabled', __('AI mapping is not enabled.', 'form-connector'));
		}

		// Build cache key from form fields + carehq fields
		$cache_key = self::build_cache_key($form_fields, $carehq_fields);

		// Check transient cache
		$cached = get_transient($cache_key);
		if ($cached !== false && is_array($cached)) {
			return $cached;
		}

		// Call the backend server
		$client   = new BackendAIClient();
		$start    = microtime(true);
		$response = $client->suggest_mappings($form_fields, $carehq_fields);
		$latency_ms = round((microtime(true) - $start) * 1000);

		if (is_wp_error($response)) {
			return $response;
		}

		// The backend returns the suggestions already parsed.
		// Validate and filter against known fields for safety.
		$suggestions = $response['data']['suggestions'] ?? $response['suggestions'] ?? [];
		$form_field_ids = array_map(fn($f) => (string) ($f['id'] ?? ''), $form_fields);
		$carehq_keys    = array_keys($carehq_fields);
		$validated      = ResponseParser::parse_array($suggestions, $form_field_ids, $carehq_keys);

		$result = [
			'suggestions' => $validated,
			'model'       => $response['data']['model'] ?? $response['model'] ?? '',
			'latency_ms'  => (int) $latency_ms,
		];

		// Cache result
		set_transient($cache_key, $result, self::CACHE_DURATION);

		return $result;
	}

	/**
	 * Test AI connection via the backend.
	 */
	public static function test_connection(): array {
		$client = new BackendAIClient(15);
		return $client->test_connection();
	}

	// ── Cache ──

	private static function build_cache_key(array $form_fields, array $carehq_fields): string {
		$input = wp_json_encode([
			'fields'  => array_map(fn($f) => ($f['id'] ?? '') . ':' . ($f['label'] ?? ''), $form_fields),
			'targets' => array_keys($carehq_fields),
		]);

		return self::CACHE_PREFIX . md5($input);
	}

	/**
	 * Clear all AI settings (for deactivation/uninstall).
	 */
	public static function clear_settings(): void {
		delete_option(self::OPTION_ENABLED);
	}
}
