<?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;
}

/**
 * OpenAI-specific prompt builder for the Responses API.
 */
class OpenAIPromptBuilder extends Builder
{
    /**
     * Build a single text input for OpenAI Responses API.
     */
    public static function buildInputText(array $input): string
    {
        return static::buildPromptText($input);
    }

    /**
     * Build final OpenAI Responses payload.
     * Supports multipart input with images and PDFs.
     */
    public static function buildPayload(AiConfig $config, array $input): array
    {
        $text = static::buildInputText($input);
        $fileResources = $input['file_resources'] ?? [];

        // Build input - use array format if we have files, otherwise simple string
        $inputContent = static::buildInputContent($text, $fileResources);

        $payload = [
            'model' => $config->getModel(),
            'input' => $inputContent,
            'temperature' => (float)($input['temperature'] ?? $config->getTemperature()),
        ];

        $max = (int)($input['max_tokens'] ?? $config->getMaxTokens());

        if ($max > 0) {
            $payload['max_output_tokens'] = max(16, $max);
        }
        return $payload;
    }

    /**
     * Build input content - multipart array if files present, otherwise string.
     *
     * @param string $text The text prompt
     * @param FileResource[] $fileResources Array of file resources
     * @return string|array
     */
    private static function buildInputContent(string $text, array $fileResources)
    {
        if (empty($fileResources)) {
            return $text;
        }

        $parts = [];

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

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

            if ($file->isImage()) {
                // Images use input_image with image_url (data URL)
                $parts[] = [
                    'type' => 'input_image',
                    'image_url' => $file->getDataUrl(),
                ];
            } elseif ($file->isPdf()) {
                // PDFs use input_file with file_data (data URL)
                $parts[] = [
                    'type' => 'input_file',
                    'filename' => $file->getName(),
                    'file_data' => $file->getDataUrl(),
                ];
            }
        }

        return $parts;
    }
}

