#!perl6

use v6;

# Pod::To::Markdown still has some weaknesses. This script fixes various
# problems with the generated markdown for the README.md generated by this
# standard:
#
#  * Fixes unprocessed C<< >> and C< > code highlights in tables
#  * Directs class doc links to doc.perl6.org
#  * Makes the code blocks into github ```perl6``` style code blocks

my Bool $in-html = False;
my Bool $in-code = False;
my Int $indent = 0;
my Str $on-hold = '';
for $*ARGFILES.lines -> $_ is copy {

    $in-html = True  if $_ eq '<table>';
    $in-html = False if $_ eq '</table>';

    if /^(\s+) "*"/ {
        $indent = $0.chars - 1;
    }

    if /^\S/ {
        $indent = 0;
    }

    if $in-code && !m/^\s ** {$indent + 4}/ && m/^\s*\S/ {
        $in-code = False;
        $on-hold.=subst(/\s+$/, '');
        say $on-hold;
        $on-hold = '';
        say ' ' x $indent + 4*?$indent, "```\n";
    }

    if !$in-html && !$in-code && /^\s ** {$indent + 4}/ {
        $in-code = True;
        say ' ' x $indent + 4*?$indent, "```perl6";
    }

    if $in-code {
        $on-hold ~= $_ ~ "\n";
        next;
    }

    # Fixup unprocessed C<<>> and C<> tags
    .=subst(/
          "C&lt;&lt;" ( [ <-[ & ]> | "&" <!before "gt;&gt;" > ]+ ) "&gt;&gt;"
        | "C&lt;" ( [ <-[ & ]> | "&" <!before "gt;" > ]+ ) "&gt;"
    /, { "<code>{($0 // $1).trim}</code>" }, :g);

    # Fixup unprocessed links
    .=subst(/
        'L&lt;' ( <[ \w \s ]>+ ) '|' ( [ <-[ & ]> | "&" <!before "gt;" > ]+ ) '&gt;'
    /, { qq|<a href=\"$1\">{$0}</a>| }, :g);

    # Pod::To::Markdown does not handle links well at all
    sub url($n) {
        given $n {
            when 'CGI'  { 'http://www.w3.org/CGI/' }
            when 'Rack' { 'http://www.rubydoc.info/github/rack/rack/master/file/SPEC' }
            when 'WSGI' { 'https://www.python.org/dev/peps/pep-0333/' }
            when 'PSGI' { 'https://metacpan.com/pod/PSGI' }
            default     { "http://doc.perl6.org/type/$n" }
        }
    }

    .=subst(/
        'L&lt;' ( <[ \w : ]>+ ) '&gt;'
    /, { qq|<a href=\"{url($0)}\">{$0}</a>| }, :g);

    # Find links [word](word) and make them [word](http://doc.perl6.org/type/word)
    .=subst(/
        '[' ( \w+ ) '](' $0 ')'
    /, { "[$0]({url($0)})" }, :g);

    .say;
}
