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

use LLM::Prompts;

my %*SUB-MAIN-OPTS =
        :named-anywhere,
        # allow named variables at any location
        ;

#| Retrieves prompts text for given names or regexes.
multi sub MAIN(
        Str $name, #= Name of a prompt or a regex. (E.g. 'rx/ ^ Em .* /'.)
        *@args,    #= Positional arguments for the prompt (if applicable.)
        *%args,    #= Named arguments for the prompt (if applicable.)
               ) {
    my $res;

    if $name ~~ / ^ rx '/' .* '/' $ / {
        use MONKEY-SEE-NO-EVAL;
        my $rxName = EVAL $name;
        if $rxName !~~ Regex {
            die "The first argument is expected to be a string or a valid regex code."
        }
        my $fields = Whatever;
        my $pairs = False;
        if %args<fields>:exists {
            $fields = %args<fields>.split(/',' | \s/, :skip-empty)».trim
        }
        if %args<pairs>:exists {
            $pairs = so %args<pairs>
        }
        $res = llm-prompt-data($rxName, :$fields, :$pairs);
    } else {
        $res = llm-prompt($name);
    }

    given $res {
        when Callable {
            # It is assumed that that arguments of each prompt with arguments have default values
            $res = $res.(|@args, |%args);
            say $res;
        }
        when Hash {
            .say for |$res.pairs.sort(*.key);
        }
        when $_.defined {
            say $res;
        }
        default {
            $res = llm-prompt-data().keys.sort;
            say "To get all known prompt names use regex specification.";
        }
    }
}
