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

use Markdown::Grammar;

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

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

#| Converts Markdown files into Jupyter and Mathematica notebooks, and HTML, Org-mode, and Pod6 files.
multi sub MAIN(Str $input?,                           #= Input file or Markdown text.
         Str :f(:$flavor) = 'Whatever',              #= Markdown flavor. (One of 'obsidian' or 'Whatever'.)
         Str :t(:format(:$to)) = 'Whatever',         #= Format to convert to. (One of 'html', 'jupyter', 'mathematica', 'org', 'pod6', or 'Whatever'.)
         Str :l(:$default-language) = 'Whatever',    #= Default code blocks language.
         Str :r(:$raku-code-cell-name) = 'Whatever', #= Raku code cell name. (Mathematica only.)
         Bool :d(:$docked-cells) = False,            #= Should formula conversion button be added as a docked cell or not? (Mathematica only.)
         Str :o(:$output) = '',                      #= Output file; if an empty string then the result is printed to stdout.
         ) {

    my $text = $input // $*IN.slurp;

    my $flavorSpec = (!$flavor || $flavor.lc ∈ <whatever automatic>) ?? Whatever !! $flavor;

    my $defaultLang = (!$default-language || $default-language.lc ∈ <whatever automatic>) ?? Whatever !! $default-language;

    my $rakuCodeCellName = (!$raku-code-cell-name || $raku-code-cell-name.lc ∈ <whatever automatic>) ?? Whatever !! $raku-code-cell-name;

    my $toSpec = $to;
    if !$to || $to.lc ∈ <whatever automatic> {
        $toSpec = do given $output {
            when !$_.chars { 'mathematica' }
            when $_ ~~ / '.nb' / { 'mathematica' }
            when $_ ~~ / '.ipynb' / { 'jupyter' }
            when $_ ~~ / '.html' / { 'html' }
            when $_ ~~ / '.org' / { 'org' }
            when $_ ~~ / '.pod' | '.pod6' / { 'pod6' }
            when $_ ~~ / '.raku' | '.p6' / { 'raku' }
            default {
                note 'Cannot automatically determine the format to convert to.';
                'mathematica'
            }
        }
    }

    my $res = from-markdown($text,
            to => $toSpec,
            flavor => $flavorSpec,
            :$docked-cells,
            default-language => $defaultLang,
            raku-code-cell-name => $rakuCodeCellName);

    if $output.chars > 0 {
        spurt($output, $res);
    } else {
        say $res;
    }
}