#!/usr/bin/env perl6

# Example to test with:
#  generate-random-sentences DSL::Bulgarian::QuantileRegressionWorkflows::Grammar '<workflow-command>' 10 --syms='Bulgarian English'

use v6.d;

use Grammar::TokenProcessing;

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

#| Generates random sentences for a given grammar.
multi MAIN(
        Str $grammar,                        #= Grammar name or definition.
        Str :$rule-body = 'TOP',             #= Rule body (to start generation with.)
        UInt :$n = 10,                       #= Number of sentences.
        UInt :$max-iterations = 40,          #= Max number of recursive rule replacement iterations.
        UInt :$max-random-list-elements = 6, #= Max number of elements to use generate random lists.
        Str :$sep = ' ',                     #= Separator of the join literals; if 'NONE' Raku code lists are returned.
        Str :$syms  = 'English'                #= A string that is a sym or a space separated syms to concretize proto rules with.
           ) {

    my $focusGrammar;
    if $grammar ~~ / ^ \s* grammar \s+ .* / {
        use MONKEY-SEE-NO-EVAL;

        $focusGrammar = EVAL($grammar);

    } else {

        try require ::($grammar);
        if ::($grammar) ~~ Failure {
            die "Cannot find grammar named: $grammar.";
        }

        $focusGrammar = ::($grammar);
    }

    die "The first argument is expected to be of type Grammar or a string that is a valid grammar definition."
    unless $focusGrammar ~~ Grammar;

    my %focusRules = $focusGrammar.^method_table;

    # Process sep
    my $sep2 = $sep eq 'NONE' ?? Whatever !! $sep;

    # Process syms
    my @syms2 = |$syms.words;

    my @randSentences = (^$n).map({ random-sentence-generation($rule-body, %focusRules, :$max-iterations, :$max-random-list-elements, sep => $sep2, syms => @syms2)});

    if $sep eq 'NONE' {
        @randSentences = @randSentences>>.raku
    }
    say @randSentences.join("\n");
}