<?php

declare(strict_types=1);

namespace FormConnector\Integration\AI;

use FormConnector\Features\License\License;
use WP_Error;

/**
 * Backend AI Client
 *
 * Sends AI mapping requests to the FormConnector plugin backend server
 * (app.formconnector.co.uk) which proxies the request to the AI provider.
 * This allows the server to approve, rate-limit, and control AI usage.
 *
 * Authentication uses the site's license key via the x-api-key header,
 * matching the pattern used by SubmissionTracker and other backend calls.
 */
class BackendAIClient {

	/**
	 * API endpoint base
	 */
	private string $api_endpoint;

	/**
	 * License instance
	 */
	private License $license;

	/**
	 * Request timeout in seconds
	 */
	private int $timeout;

	/**
	 * @param int $timeout Request timeout in seconds (default 30)
	 */
	public function __construct(int $timeout = 30) {
		$this->license      = new License();
		$this->api_endpoint = defined('FC_LICENSE_API_ENDPOINT')
			? FC_LICENSE_API_ENDPOINT
			: 'https://app.formconnector.co.uk';
		$this->timeout      = $timeout;
	}

	/**
	 * Request AI field-mapping suggestions from the backend.
	 *
	 * @param array $form_fields  Form field descriptors (id, label, type, options)
	 * @param array $carehq_fields CareHQ field key => label pairs
	 * @return array|WP_Error Parsed suggestions or error
	 */
	public function suggest_mappings(array $form_fields, array $carehq_fields): array|WP_Error {
		$key = $this->license->get_key();
		if (empty($key)) {
			return new WP_Error(
				'ai_no_license',
				__('A valid license key is required for AI mapping suggestions.', 'form-connector')
			);
		}

		// Build a clean payload — only field metadata, never submission data
		$fields_payload = array_map(function ($field) {
			$entry = [
				'id'    => (string) ($field['id'] ?? ''),
				'label' => (string) ($field['label'] ?? ''),
				'type'  => (string) ($field['type'] ?? 'text'),
			];
			if (!empty($field['options']) && is_array($field['options'])) {
				$entry['options'] = array_map(
					fn($opt) => is_array($opt) ? ($opt['label'] ?? $opt['value'] ?? '') : (string) $opt,
					array_slice($field['options'], 0, 20)
				);
			}
			return $entry;
		}, $form_fields);

		$payload = [
			'form_fields'   => $fields_payload,
			'carehq_fields' => $carehq_fields,
			'site_url'      => get_site_url(),
		];

		$url = rtrim($this->api_endpoint, '/') . '/api/ai/suggest-mappings';

		$response = wp_remote_post($url, [
			'timeout' => $this->timeout,
			'headers' => [
				'x-api-key'    => $key,
				'Content-Type' => 'application/json',
				'Accept'       => 'application/json',
			],
			'body' => wp_json_encode($payload),
		]);

		if (is_wp_error($response)) {
			return new WP_Error(
				'ai_network_error',
				__('Failed to connect to FormConnector AI service: ', 'form-connector') . $response->get_error_message()
			);
		}

		$code = wp_remote_retrieve_response_code($response);
		$body = wp_remote_retrieve_body($response);
		$data = json_decode($body, true);

		if (!is_array($data)) {
			return new WP_Error(
				'ai_invalid_response',
				__('Invalid response from FormConnector AI service.', 'form-connector')
			);
		}

		if ($code === 402) {
			return new WP_Error(
				'ai_not_available',
				$data['message'] ?? __('AI mapping is not available on your current plan.', 'form-connector')
			);
		}

		if ($code === 429) {
			return new WP_Error(
				'ai_rate_limited',
				$data['message'] ?? __('AI request limit reached. Please try again later.', 'form-connector')
			);
		}

		if ($code < 200 || $code >= 300) {
			$message = $data['message'] ?? sprintf(__('AI service returned HTTP %d', 'form-connector'), $code);
			return new WP_Error('ai_api_error', $message, ['status_code' => $code]);
		}

		return $data;
	}

	/**
	 * Test the AI service connection via the backend.
	 *
	 * @return array Result with success status and message
	 */
	public function test_connection(): array {
		$key = $this->license->get_key();
		if (empty($key)) {
			return [
				'success' => false,
				'message' => __('A valid license key is required.', 'form-connector'),
			];
		}

		$url = rtrim($this->api_endpoint, '/') . '/api/ai/test-connection';

		$response = wp_remote_post($url, [
			'timeout' => 15,
			'headers' => [
				'x-api-key'    => $key,
				'Content-Type' => 'application/json',
				'Accept'       => 'application/json',
			],
			'body' => wp_json_encode(['site_url' => get_site_url()]),
		]);

		if (is_wp_error($response)) {
			return [
				'success' => false,
				'message' => __('Failed to connect: ', 'form-connector') . $response->get_error_message(),
			];
		}

		$code = wp_remote_retrieve_response_code($response);
		$body = wp_remote_retrieve_body($response);
		$data = json_decode($body, true);

		if ($code >= 200 && $code < 300 && !empty($data['success'])) {
			return [
				'success' => true,
				'message' => $data['message'] ?? __('AI service connected successfully.', 'form-connector'),
			];
		}

		return [
			'success' => false,
			'message' => $data['message'] ?? sprintf(__('AI service returned HTTP %d', 'form-connector'), $code),
		];
	}
}
