<?php

namespace OtomaticAi\Models\Presets;

use OtomaticAi\Api\Gemini\Client as GeminiClient;
use OtomaticAi\Api\Gemini\PoolClient as PoolGeminiClient;
use OtomaticAi\Vendors\Illuminate\Support\Arr;

class GeminiPreset extends Preset
{
    /**
     * Create the Gemini API payload
     *
     * @param array $params
     * @return array
     */
    public function payload(array $params = []): array
    {
        $model = $this->model;

        switch ($model) {
            case "gemini-2.5-pro":
                $model = "gemini-2.5-pro";
                break;
            case "gemini-2.5-flash":
                $model = "gemini-2.5-flash";
                break;
            case "gemini-2.5-flash-lite":
                $model = "gemini-2.5-flash-lite";
                break;
            case "gemini-3-pro":
                $model = "gemini-3-pro-preview";
                break;
            case "gemini-3-flash":
                $model = "gemini-3-flash-preview";
                break;
        }

        $messages = $this->replaceMessagesVariables($params);
        $messages = array_map(function ($message) {
            return ["text" => $message["content"]];
        }, $messages);

        $payload = [
            "model" => $model,
            "contents" => [
                ["parts" => $messages]
            ],
        ];

        return $payload;
    }

    public function process(array $params = [])
    {
        $api = new GeminiClient;

        $response = $api->chat($this->payload($params));
        Arr::set($response, "choices.0.message.content", Arr::get($response, "candidates.0.content.parts.0.text"));

        return $response;
    }

    public function processPool(array $params = [])
    {
        $api = new PoolGeminiClient;
        $params = array_map(function ($p) {
            return $this->payload($p);
        }, $params);

        $responses = $api->chat($params);
        $responses = array_map(function ($response) {
            Arr::set($response, "choices.0.message.content", Arr::get($response, "candidates.0.content.parts.0.text"));
            return $response;
        }, $responses);

        return $responses;
    }
}
