<?php
namespace boru\boruai\Models\Tool;

use boru\boruai\BoruAI;
use boru\boruai\Openai\Response\Parts\FunctionCall;
use boru\boruai\Openai\Response\Parts\OutputMessage;

class AsyncToolHandler extends ToolHandler {
    /**
     * Handles a message or array of messages, processes any tool calls, and stores tool call responses
     * @param OutputMessage|OutputMessage[] $messages 
     * @param array $options 
     * @return string 
     */
    public function handle($messages, $options=[]) {
        BoruAI::initTaskQueue();
        foreach($messages as $message) {
            if($message instanceof FunctionCall) {
                $this->addToolMessage($message);
                $functionData = $message->toArray();
                $functionData['type'] = 'function_call.started';
                $this->makeEvent($functionData);
                //Output::outLine("Function Call ID: ",$message->id());
                //Output::outLine("Function Call Name: ",$message->name());
                $data = $message->run();
                if($data) {
                    $this->haveToolCalls(true);
                    $this->addToolResult($message->id(),$data);
                    $functionData['type'] = 'function_call.completed';
                    $functionData['output'] = isset($data["output"]) ? $data["output"] : null;
                    $this->makeEvent($functionData);
                } else {
                    $functionData['type'] = 'function_call.failed';
                    $this->makeEvent($functionData);
                }
            }
        }
    }
}