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

use Lingua::StopwordsISO;
use JSON::Fast;

multi format-output(Str $format, $output) {
    given $format.lc {
        when $output.elems == 1 && $output ~~ Hash         { format-output($format, $output.values[0]); }
        when $_ (elem) <string text> && $output ~~ SetHash { say $output.keys.sort.join(' '); }
        when $_ (elem) <string text> && $output ~~ Hash    { say to-json($output.map({ $_.key => $_.values.sort.join(' ') })); }
        when $_ (elem) <json> && $output ~~ SetHash        { say to-json($output.keys.sort); }
        when $_ (elem) <json> && $output ~~ Hash           { say to-json($output.deepmap(*.keys.sort)); }
        default                                            { say $output.raku; }
    }
}

#| Gives stop words for the specified languages in the specified format.
multi sub MAIN(*@langs,                            #= Languages to get the stop words for.
               Str :f(:$format) = 'text'           #= Output format one of 'text', 'json', or 'raku'.
               ) {
    my %res = stopwords-iso(@langs);
    return format-output($format, %res);
}

#| Gives stop words for language specs in (pipeline) input.
multi sub MAIN(Str :f(:$format) = 'text'           #= Output format one of 'text', 'json', or 'raku'.
               ) {
    my @langs = lines.join(' ').words;
    return format-output($format, stopwords-iso(@langs));
}