<?php
namespace boru\boruai\Cli\Defs;

use boru\boruai\BoruAI;
use boru\boruai\Models\ChatSession;
use boru\boruai\Models\Document;
use boru\boruai\Models\Queue;
use boru\cli\CLI;
use boru\cli\params\Flag;
use boru\cli\params\Option;
use boru\cli\params\Positional;
use boru\output\Output;
use boru\boruai\Openai\Api\Endpoints\AssistantsAPI;
use boru\boruai\Openai\OpenAIAssistant;
use boru\boruai\Openai\OpenAIChat;

trait DocumentCLI {
    public static function def_document() {
        return [
            "description"=> "Document Management Operations",
            "params" => [
            ]
        ];
    }

    public static function def_document_list() {
        return [
            "description"=> "List Documents",
            "params" => [
                Option::create("l|limit|The number of sessions to list",["default"=>25]),
                Option::create("o|offset|The offset to start listing from",["default"=>0]),
            ]
        ];
    }

    public function cmd_document_list($cmd) {
        $limit = $cmd->get("limit",25);
        $offset = $cmd->get("offset",0);
        $documents = Document::listDocuments($limit,$offset);
        foreach($documents as $document) {
            Output::outLine($document->id()."\t".$document->filename());
        }
    }

    public static function def_document_add() {
        return [
            "description"=> "Add a document",
            "params" => [
                Positional::create("file|The file to add (full path)"),
                Option::create("u|userid|The user ID to associate with the document",["default"=>0]),
                Option::create("r|reference|A reference to associate with the document"),
                Flag::create("f|force|Force the document to be added (don't check for duplicates)"),
                Flag::create("ocr|OCR the document"),
                Flag::create("nopages|Do not convert the document to pages"),
            ]
        ];
    }

    public function cmd_document_add($cmd) {
        $file = $cmd->get("file");
        $userid = $cmd->get("userid",0);
        $reference = $cmd->get("reference","");
        $force = $cmd->get("force",false);
        $ocr = $cmd->get("ocr",false);
        $nopages = $cmd->get("nopages",false);
        $options = [
            "userId"=>$userid,
            "dupeCheck"=>!$force
        ];
        $document = Document::create($file,$reference,$options);
        $document->generateFiles(!$nopages);
        if($ocr) {
            //$document->upload(true);
            $files = $document->files();
            foreach($files as $file) {
                Queue::queue($file,"ocr");
            }
            Output::outLine("Document added:",$document->id(),"and OCR queued");
        } else {
            Output::outLine("Document added:",$document->id());
        }
        
    }
}