#!/usr/bin/env raku
use v6.d;

use Chatnik;
use JSON::Fast;

#-----------------------------------------------------------

my %*SUB-MAIN-OPTS = :named-anywhere;

sub is-known-chat-id(Str:D $word) {
    my %chats = from-json(slurp(Chatnik::get-chat-objects-file-name));
    return %chats{$word}:exists
}

#| Chat with persistent LLM-chat objects.
multi sub MAIN(
        Str:D $input, #= Chat input text.
        *%args,       #= LLM configuration named arguments.
         ) {

    # Ingest the chat objects
    my %chats = %();
    if Chatnik::get-chat-objects-file-name.IO.f {
        # Has to be optimized soon -- it is ineffective to create all chat objects.
        %chats = Chatnik::import-chats()
    }

    # Evaluate message
    my $res = Chatnik::evaluate-message($input, %chats, |%args);

    # Export chat objects
    Chatnik::export-chats(%chats);

    # Print results
    say $res;
}

#| Using multiple words as input.
multi sub MAIN(
        *@words,   #= Multi-word input.
        *%args     #= LLM configuration named arguments.
               ) {
    if %args.elems == 0 && @words.elems > 1 && is-known-chat-id(@words.head) {
        return MAIN(@words.tail(*-1), chat-id => @words.head)
    }
    return MAIN(@words.join(' '), |%args)
}

#| Using shell pipeline value as input.
multi sub MAIN(
        *%args     #= LLM configuration named arguments.
               ) {
    return MAIN(lines().join("\n"), |%args)
}