### ----------------------------------------------------
### -- Jupyter::Chatbook
### -- Licenses: Artistic-2.0
### -- Authors: Brian Duggan, Anton Antonov
### -- File: lib/Jupyter/Chatbook/Magics.rakumod
### ----------------------------------------------------
### -- Chunk 2 of 2
match<magic><always> {
        $match = Jupyter::Chatbook::Magic::Grammar.new.parse($code,:$actions);
        $code = '';
        # Parse only first line otherwise
    } else {
        $code .= subst( $magic-line, '');
        $code .= subst( /\n/, '');
    }
    return $match.made;
}

method find-magic($code is rw) {
    # Parse
    my $magic-action = self.parse-magic($code);
    # If normal line and there is always magics -> activate them
    if !$magic-action && ($always.prepend || $always.append) {
        return Magic::AlwaysWorker.new;
    }
    return $magic-action;
}

method get-user-llm-personas(--> Map:D) {
    my $base = %*ENV<XDG_HOME> // $*HOME.child('.config');
    $base = $base.child('raku-chatbook') // $*HOME.child('.config');
    my $conf-file = %*ENV<RAKU_CHATBOOK_LLM_PERSONAS_CONF> // $base.child('llm-personas.json');
    if $conf-file.IO.e {
        #debug "Reading configuration from $conf-file";
        try {
            my @specs = |from-json($conf-file.IO.slurp);
            if @specs ~~ (List:D | Array:D | Seq:D) && @specs.all ~~ Map:D {
                # Merge magic arguments with defaults
                my %personas = do for @specs.kv -> $i, %p {
                    # Merge with defaults
                    my %h = %(conf => 'ChatGPT', chat-id => "p$i" ), %p;
                    # Expand prompt
                    if %h<prompt>:exists {
                        %h<prompt> = llm-prompt-expand(%h<prompt>)
                    }
                    # Make a chat object
                    %h<chat-id> => llm-chat(|%h);
                }
                return %personas;
            }
        }
    }
    return %();
}


