<?php
namespace boru\boruai\UI\Actions;

use boru\boruai\Models\Response;
use boru\boruai\Openai\Response\ResponseObject;

class ChatAction extends Ajax {
    private function createResponse() {
        $webUI = $this->getWebUI();
        $tools = $webUI->getTools(true);
        $perUserReference = $webUI->config("per_user_reference", true);
        if($perUserReference) {
            $response = Response::withReference($this->reference(), $this->user()->id());
        } else {
            $response = Response::withReference($this->reference());
        }
        $response->model("gpt-4.1");
        if($tools) {
            foreach($tools as $tool) {
                $response->addTool($tool);
            }
        }
        return $response;
    }

    private function getMessage() {
        $webUI = $this->getWebUI();
        $message = $this->request("message");
        if(!$message) {
            $message = $this->body("message");
        }
        return $webUI->mergeText($message);
    }

    private function getInstructions() {
        $webUI = $this->getWebUI();
        $instructions = $webUI->getInstructions(true);
        if($instructions) {
            if(is_string($instructions)) {
                return $instructions;
            }
            if(is_array($instructions)) {
                $string = "";
                if(count($instructions) > 1) {
                    foreach($instructions as $key => $value) {
                        if(is_array($value)) {
                            $value = json_encode($value,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
                        }
                        if(is_string($key)) {
                            $string .= $key.": ".$value."\n";
                        } else {
                            $string .= $value."\n";
                        }
                    }
                } else {
                    $instructions = array_shift($instructions);
                    if(is_array($instructions)) {
                        $string = json_encode($instructions,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
                    } else {
                        $string = $instructions;
                    }
                }
                return $webUI->mergeText($string);
            }
        }
        return false;
    }

    public function handle() {
        static::init(true);
        //$response = new Response();
        
        $response = $this->createResponse();
        $message = $this->getMessage();
        $instructions = $this->getInstructions();
        
        if(!$message) {
            if($instructions) {
                $message = $instructions;
                $instructions = false;
            } else {
                Ajax::error($response, "No message provided");
                return;
            }
        }
        if($instructions) {
            $response->instructions($instructions);
        }
        $response->addMessage($message);
        $response->create(null, function($streamEvent) {
            $array = $streamEvent->toArray();
            
            if(isset($array["response"])) {
                if($array["type"] == "reponse.complete") {
                    $obj = new ResponseObject($array["response"]);
                    $result = $obj->getResult(true);
                    $array["response"]["output_as_string"] = $result;
                }
                if(isset($array["response"]["id"])) {
                    $responseId = $array["response"]["id"];
                    $array["response_id"] = $responseId;
                }
                unset($array["response"]);
            }
            
            echo "data: ".json_encode($array,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE)."\n\n";
            flush();
        });
        return;
    }
}