<?php

namespace OtomaticAi\Models\Presets;

use OtomaticAi\Api\Anthropic\Client as AnthropicClient;
use OtomaticAi\Api\Anthropic\PoolClient as PoolAnthropicClient;
use OtomaticAi\Vendors\Illuminate\Support\Arr;

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

        switch ($model) {
            case "claude-4-6-opus":
                $model = "claude-opus-4-6";
                $maxTokens = 128000;
                break;
            case "claude-4-5-sonnet":
                $model = "claude-sonnet-4-5-20250929";
                $maxTokens = 64000;
                break;
            case "claude-4-5-haiku":
                $model = "claude-haiku-4-5-20251001";
                $maxTokens = 64000;
                break;
        }

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

        $messages = [
            [
                "role" => "user",
                "content" => implode("\n\n", $messages)
            ]
        ];

        $payload = [
            "model" => $model,
            "stream" => false,
            "messages" => $messages,
            "max_tokens" => $maxTokens,
        ];

        return $payload;
    }

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

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

        return $response;
    }

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

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

        return $responses;
    }
}
