<?php
namespace boru\boruai\Api\Session;

use boru\boruai\Api\BaseAPI;
use boru\boruai\Models\ChatSession;
use boru\boruai\Models\Document;
use boru\boruai\BoruAI;
use boru\dhapi\core\Dispatcher;

class SessionChatAPI extends BaseAPI {

    public function execute() {
        $sessionIdOrName = $this->get("session", false);
        return $this->success(["sessionIdOrName" => $sessionIdOrName]);
        $session = $this->initializeSession($sessionIdOrName);
        
        // Assuming the API method can accept a command string
        $input = $this->body("input", ""); 
        $responseMessage = $this->handleChat($session, $input);
        
        return $this->success($responseMessage);
    }

    private function initializeSession($sessionIdOrName) {
        $session = null;
        
        if ($sessionIdOrName != "new") {
            $session = ChatSession::fromName($sessionIdOrName) ?: ChatSession::fromId($sessionIdOrName);
        }

        if (!$session) {
            $session = new ChatSession(["name" => $sessionIdOrName === "new" ? md5(time()) : $sessionIdOrName]);
            $session->save();
        }

        return $session;
    }
    
    private function handleChat($session, $chatInput) {
        if (empty($chatInput)) return "No command provided.";

        $lines = explode("\n", $chatInput);
        foreach ($lines as $i => $line) {
            if (substr($line, 0, 1) == ":") {
                $cmdParts = explode(" ", substr($line, 1));
                // Handle document, include and tool commands
                switch ($cmdParts[0]) {
                    case 'doc':
                    case 'document':
                        if (count($cmdParts) == 2) {
                            $doc = Document::fromId($cmdParts[1]);
                            if ($doc) {
                                $session->addDocument($doc);
                            }
                        }
                        unset($lines[$i]);
                        break;
                    case 'tool':
                        if (count($cmdParts) == 2) {
                            $tool = BoruAI::loadTool($cmdParts[1]);
                            if ($tool) {
                                $session->addTool($cmdParts[1]);
                            }
                        }
                        unset($lines[$i]);
                        break;
                }
            }
        }
        
        if (empty($lines)) {
            return "No chat message to process.";
        }

        $phrase = implode("\n", $lines);
        $response = $session->chat($phrase);
        
        return $response;
    }
}