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

use Jupyter::Converter;

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

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

#| Converts Jupyter notebooks into Markdown, HTML, and Pod6 files.
sub MAIN(Str:D $text,                                    #= Input file or Jupyter notebook text.
         Str:D :t(:format(:$to)) = 'Whatever',           #= Format to convert to. (One of 'html', 'markdown', 'mathematica', 'org-mode', 'pod6', 'raku', or 'Whatever'.)
         Str:D :img-dir(:$image-directory) = 'Whatever', #= Directory to export images to.
         Str:D :m(:$method) = 'Whatever',                #= Method of conversion. (One of 'delegation' or 'Whatever'.)
         Str:D :o(:$output) = '',                        #= Output file; if an empty string then the result is printed to stdout.
         *%args,                                         #= Arguments to pass to `from-markdown`.
         ) {

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

    # Process the other options
    my $img-dir = $image-directory.lc ∈ <whatever auto automatic> ?? Whatever !! $image-directory;
    my $m = $method.lc ∈ <whatever auto automatic> ?? Whatever !! $method;

    # Main call
    my $res = from-jupyter($text, target => $toSpec, image-directory => $img-dir, method => $m, delegation-args => %args);

    # Write to file or print
    if $output.chars > 0 {
        spurt($output, $res);
    } else {
        say $res;
    }
}