<?php

namespace ZenoChatbot\Services\LLMService\AIClient\Support;

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

/**
 * Shared utilities for parsing LLM responses.
 */
class ResponseParser
{
    /**
     * Extract citation references from candidate responses.
     *
     * Looks for patterns like [source: filename.pdf] in the response text.
     *
     * @param array $candidates Array of Candidate objects
     * @return array Unique citation references
     */
    public static function extractCitations(array $candidates): array
    {
        $out = [];
        foreach ($candidates as $c) {
            $txt = $c->getText();
            if (preg_match_all('/\[source:\s*([^\]]+)\]/i', $txt, $m)) {
                foreach ($m[1] as $s) {
                    $out[] = trim($s);
                }
            }
        }
        return array_values(array_unique($out));
    }

    /**
     * Sanitize request payload for storage (remove sensitive data).
     *
     * Extracts common input fields and merges with provider-specific payload structure.
     *
     * @param array $input The input data
     * @param array $payloadStructure Provider-specific payload structure info
     * @return array Sanitized request data
     */
    public static function sanitizeRequest(array $input, array $payloadStructure = []): array
    {
        return [
            'message'           => $input['message'] ?? '',
            'system_prompts'    => $input['system_prompts'] ?? [],
            'context_count'     => count($input['context'] ?? []),
            'resources_count'   => count($input['resources'] ?? []),
            'temperature'       => $input['temperature'] ?? null,
            'max_tokens'        => $input['max_tokens'] ?? null,
            'payload_structure' => $payloadStructure,
        ];
    }
}

