<?php

namespace ZenoChatbot\Services\LLMService\AIClient\Providers\PromptBuilders;

use ZenoChatbot\Services\LLMService\AIClient\Config\AiConfig;
use ZenoChatbot\Services\LLMService\AIClient\Support\FileResource;

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

/**
 * Gemini-specific prompt builder for the generateContent API.
 */
class GeminiPromptBuilder extends Builder
{
    /**
     * Build Gemini contents array for a single-turn input.
     * Supports multipart content with images and PDFs.
     */
    public static function buildContents(array $input): array
    {
        $text = static::buildPromptText($input);
        $fileResources = $input['file_resources'] ?? [];

        $parts = static::buildParts($text, $fileResources);

        return [
            ['role' => 'user', 'parts' => $parts]
        ];
    }

    /**
     * Build final Gemini payload including contents and generationConfig.
     */
    public static function buildPayload(AiConfig $config, array $input): array
    {
        return [
            'contents' => static::buildContents($input),
            'generationConfig' => [
                'temperature' => (float)($input['temperature'] ?? $config->getTemperature()),
                'maxOutputTokens' => (int)($input['max_tokens'] ?? $config->getMaxTokens()),
                'candidateCount' => (int)($input['candidate_count'] ?? 1),
            ],
        ];
    }

    /**
     * Build parts array with text and inline_data for files.
     *
     * @param string $text The text prompt
     * @param FileResource[] $fileResources Array of file resources
     * @return array
     */
    private static function buildParts(string $text, array $fileResources): array
    {
        $parts = [];

        // Add text part first
        if ($text !== '') {
            $parts[] = ['text' => $text];
        }

        // Add file parts as inline_data
        foreach ($fileResources as $file) {
            if (!$file instanceof FileResource) {
                continue;
            }

            // Gemini uses inline_data for both images and PDFs
            $parts[] = [
                'inline_data' => [
                    'mime_type' => $file->getMimeType(),
                    'data' => $file->getBase64Data(),
                ],
            ];
        }

        return $parts;
    }
}

