<?php

declare(strict_types=1);

namespace FormConnector\Integration\AI;

/**
 * Prompt Builder for AI field mapping suggestions.
 *
 * Builds deterministic system and user prompts that instruct the model
 * to return a strict JSON mapping from form fields to CareHQ fields.
 * Only field metadata (id, label, type, option labels) is ever sent —
 * no submission data or PII.
 */
class PromptBuilder {

	/**
	 * Build the system prompt.
	 *
	 * @param array $carehq_fields Associative array of CareHQ field key => label
	 * @return string
	 */
	public static function system(array $carehq_fields): string {
		$field_list = '';
		foreach ($carehq_fields as $key => $label) {
			$field_list .= sprintf("  - \"%s\" (%s)\n", $key, $label);
		}

		return <<<PROMPT
You are a field-mapping assistant for a CRM integration.
Your job is to match web form fields to CRM (CareHQ) contact fields.

Available CareHQ target fields:
{$field_list}
Rules:
1. Return ONLY valid JSON — no markdown, no explanation, no extra text.
2. The JSON must be an object where each key is the form field "id" and the value is an object with:
   - "target": the CareHQ field key it maps to, or "" if no match
   - "confidence": a number 0.0–1.0
   - "reason": a short explanation (max 15 words)
3. Every form field must appear exactly once in the output.
4. Each CareHQ target field should be used at most once (pick the best match).
5. Set confidence < 0.3 and target "" for fields that don't match anything.
6. Consider field labels, types, and option values when deciding matches.
PROMPT;
	}

	/**
	 * Build the user prompt.
	 *
	 * @param array $form_fields Array of form field descriptors
	 *                           Each: ['id' => string, 'label' => string, 'type' => string, 'options' => array|null]
	 * @return string
	 */
	public static function user(array $form_fields): string {
		$fields_json = [];
		foreach ($form_fields as $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) // Limit options to avoid huge prompts
				);
			}
			$fields_json[] = $entry;
		}

		$json = wp_json_encode($fields_json, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

		return "Map these form fields to CareHQ fields. Return ONLY a JSON object.\n\nForm fields:\n{$json}";
	}
}
