use v6.d;
use Data::Dump::Tree;
use JSON::Fast;
use RakuDoc::Citations;
use experimental :rakuast;
my @q-code-raw =
    'rakudoc-evo-chapter',
    'NoCitation',
    'JSONvsXMLmeta',
    '10.1109/MODELS50736.2021.00031',
#    'Apocalypse1; P6&Parrot; ConwayKeynote2010',
    'rakudoc-evo-chapter, pp. 32-47',
    '10.1109/MODELS50736.2021.00031, sect. III',
#    'Apocalypse1; P6&Parrot, ch. 1; ConwayKeynote2010, ts=00:03:27',
;
my %q-codes = @q-code-raw.map({ 'key_' ~ $++ => $_ });
my %citations = $=finish.EVAL;

#my $style = 'ieee';
my $style = "acm-siggraph";
my $lang = %citations<locale> // 'en-GB';
my @warnings;

my token indic {
    <-[,;|\\]>+   # or non-special characters
}

# What the optional suffix in a Q<> looks like...
my token suffix {
    # Same pattern as above, except raw commas are allowed...
    <-[;|\\]> *
}
my $next-missing = 1;
my @citations = gather for %q-codes.sort -> (:$key, :value($raw)) {
    my $inf = $raw ~~ / ^ [ $<term>=(<indic> [ ',' \s* <suffix> ]?) [\s* ';' \s*]? ]+ $/;
    my @citation-items = gather for $inf.<term> {
        my $id = .<indic>.Str;
        my $suffix = .<suffix> ?? ', ' ~ .<suffix> !! '';
        %citations<data>{$id} //= citation-placeholder($id, 'NO SUCH CITATION ID');
        %citations<categories><cited>{ $id }++;
        take %( :$id, :$suffix );
    }
    take @citation-items;
}
%citations<categories><uncited> = %citations<data>.keys (-) %citations<categories><cited>;
my @references = gather for %citations<categories><cited>.keys -> $id {
    take test-citation( $id, %citations<data>{ $id }, @warnings )
}
my %input = :@citations, :$lang, :$style, :@references ;
my $input-json = to-json( %input );

# Run citeproc to generate the final renderings...
my $citeproc = citeproc($input-json,$style);
my %cit-output = from-json $citeproc;
#$!current<warnings>.append( %cit-output<warnings> ) if %cit-output<warnings>.elems;

# Retrieve and translate the markers back to RakuDoc...
my @markers = %cit-output<citations>.list
        .map({ "=begin rakudoc\n" ~ csl-json-to-rakudoc( $_ ) ~ "\n=end rakudoc"})
#        .map( *.AST.rakudoc.head.paragraphs.head )
;
# Retrieve and translate the bibliographic list back to RakuDoc...
my @biblist = %cit-output<bibliography>.list
        .map({ "=begin rakudoc\n" ~ csl-json-to-rakudoc( $_[1], :id( $_[0] ~ '__citation-link') ) ~ "\n=end rakudoc"})
#        .map({ .AST.rakudoc.head.paragraphs.head.gist })
;
@warnings.append: %cit-output<warnings>.flat;
say 'Markers';
.say for @markers;
say 'Biblio';
.say for @biblist;
say 'Warnings';
.say for @warnings;


=finish
{
    :categories(${:CSL($["rakudoc-evo-chapter", "JSONvsXMLmeta", "Missing-ID-1", "starlight2024", "tlhInganHol::yIghun", "Perligata"]), :JSON($["Missing-ID-1"]), :Raku($["rakudoc-evo-chapter", "JSONvsXMLmeta"]), :TeX($["mercurio2026"]), :XML($["Vasiliev26"]), :medical($["Vasiliev26"]), :tagged($["thorne2023"])}),
    :data(
        ${
        "10.1109/MODELS50736.2021.00031" => ${
            :DOI("10.1109/MODELS50736.2021.00031"),
            :author($[
                {:family("García-Domínguez"), :given("Antonio")},
                {:family("Worthington"), :given("Jonathan")}
            ]),
            :container-title("2021 International Conference on Model Driven Engineering Languages and Systems (MODELS)"),
            :id("10.1109/MODELS50736.2021.00031"),
            :issued(%({:year(2021)}, {:year(10)})),
            :note("A pivotal paper describing the formal grammar and model-driven approach to RakuDoc."),
            :page("233-243"),
            :publisher("IEEE"),
            :title("Model-Driven Development of Documentation: The Case of RakuDoc"),
            :type("paper-conference")
        },
        :AbsentFriends(${:author(${:family("Unknown"), :given("Reference")}), :container-title("Did you misspell <AbsentFriends>?"), :id("AbsentFriends"), :issued(${:date-parts($[1])}), :title("NO SUCH CITATION ID: AbsentFriends"), :type("article")}),
        :Alias2023(${:DOI("10.0000/raku.isrt.2023.42"), :abstract("Investigates the cognitive load required for veteran developers to stop typing 'p6' and start embracing the 'raku' CLI alias."), :author($[{:family("Nym"), :given("Sara")},]), :event-title("International Symposium on Renaming Things"), :id("Alias2023"), :issued($[{:month(6), :year(2023)},]), :title("Wait, what's it called now? A Longitudinal Study of Developer Confusion"), :type("paper-conference")}),
        :Apocalypse1(${:URL("https://www.perl.com/pub/2001/04/02/apocalypse1.html/"), :author(${:family("Wall"), :given("Larry")}), :id("Apocalypse1"), :issued($[{:year(2001)}, {:year(4)}, {:year(2)}]), :note("Initial design document for Perl 6 based on RFCs."), :publisher("Perl.com"), :title("Apocalypse 1"), :type("article-journal")}),
        :Butterfly2019(${:abstract("An empirical study on the reduction of mouth-strain when moving from a liquid 'l' in 'Perl' to the punchy, k-centric satisfaction of 'Raku'."), :author($[{:family("Vowels"), :given("Aria")}, {:family("Glottis"), :given("Stop")}]), :container-title("The Journal of Arbitrary Orthography"), :id("Butterfly2019"), :issue("3"), :issued($[{:day(15), :month(10), :year(2019)},]), :page("101-115"), :title("The Camelia Transition: A Phonetic Analysis of 'Raku' vs. 'Perl'"), :type("article-journal"), :volume("42")}),
        :ConwayKeynote2010(${:author(${:family("Conway"), :given("Damian")}), :event("The Perl Conference (YAPC::NA 2010)"), :event-place("Columbus, Ohio, USA"), :id("ConwayKeynote2010"), :issued($[{:year(2010)}, {:year(6)}]), :title("ReDeveloping in Perl 6"), :type("speech")}),
        :Generic2026(${:ISSN("1234-567X"), :URL("http://www.ncbi.nlm.nih.gov/pubmed/98765432"), :author($[{:family("Generic"), :given("A.")}, {:family("Researcher"), :given("B.")}]), :container-title("International Journal of Perl and Raku"), :id("Generic2026"), :issue("1"), :issued($[{:day(30), :month(1), :year(2026)},]), :page("102-115"), :title("Concurrent processing in RakuDoc: A performance analysis."), :title-short("Concurrent processing in RakuDoc"), :type("article-journal"), :volume("14")}),
        :JSONvsXMLmeta(${
            :DOI("10.1000/jdh.2024.03.01"),
            :author(${
                :ORCID("0000-0001-2345-6789"),
                :family("Doe"),
                :given("John")},
            ),
            :container-title($("Journal", "of", "Digital", "Humanities")),
            :id("JSONvsXMLmeta"),
            :issue(3),
            :issued({:year(2024),}),
            :note($("Fields", "can", "also", "be", "specified", "as", "adverbial", "pairs")),
            :page("101-115"),
            :title($("A", "Performance", "Analysis", "of", "JSON", "vs", "XML", "in", "Academic", "Metadata")),
            :type("article-journal"),
            :volume(12)
        }),
        "Missing-I2" => ${:author($[{:family("Willighagen"), :given("Lars")},]), :id("Missing-ID-2"), :issued($[{:day(2), :month(5), :year(2020)},]), :publisher("GitHub Gist"), :title("Example CSL-JSON file"), :type("article")},
        "P6\&Parrot" => ${:ISBN("978-0596007379"), :author($[{:family("Randal"), :given("Allison")}, {:family("Sugalski"), :given("Dan")}, {:family("Tötsch"), :given("Leopold")}]), :edition("2nd"), :id("P6\&Parrot"), :issued($[{:year(2004)}, {:year(7)}]), :publisher("O'Reilly Media"), :title("Perl 6 and Parrot Essentials"), :type("book")},
        :Perligata(${:ISBN("0-596-00013-8"), :author(${:family("Conway"), :given("Damian")}), :event-place("Monterey, CA, USA"), :event-title("Proceedings of the Perl Conference 4.0"), :id("Perligata"), :issued($[{:month(7), :year(2000)},]), :page("1-15"), :publisher("O'Reilly and Associates"), :publisher-place("CA, USA"), :title("Lingua::Romana::Perligata -- Perl for the XXI-imum Century"), :type("paper-conference")}),
        :RD-citations_missing(${:author(${:family("Unknown"), :given("Reference")}), :container-title("Did you misspell <RD-citations_missing>?"), :id("RD-citations_missing"), :issued(${:date-parts($[1])}), :title("NO SUCH CITATION ID: RD-citations_missing"), :type("article")}),
        :RakudoWay2021(${:author($[{:family("Implementation"), :given("Lars")},]), :id("RakudoWay2021"), :issued($[{:year(2021)},]), :note("A deep dive into the Japanese etymology of 'Rakudo' (The Way of Raku) and why implementations should sound like martial arts."), :publisher("Optimized Path Press"), :publisher-place("Vienna"), :title("Rakudo: The Way of the Camel-less"), :type("book")}),
        :Vasiliev26(${:author($[{:family("Vasiliev"), :given("Elena")},]), :id("Vasiliev26"), :issued($[{:year(2026)},]), :publisher("Deep Space Coding Collective"), :title("Functional purity in a multi-paradigm world"), :type("report")}),
        :fluffington2024uncited(${:ISBN("978-0-12345-678-X"), :author(${:family("Fluffington"), :given("Barnaby")}), :edition("3rd (Expanded with 500 unnecessary sources)"), :id("fluffington2024uncited"), :issued($[{:year(2024)}, {:year(1)}]), :note("A satirical look at the inflation of reference lists in modern academia."), :publisher("Vaporware Academic Press"), :title("Uncited Unsighted: The Art and Science of Padding your Bibliography"), :type("book")}),
        :hu2023malfeasance(${:URL("https://husez.fm/ep/detecting-malfeasance"), :author(${:family("Hu"), :given("Wilson")}), :container-title("Hu Sez"), :episode(42), :id("hu2023malfeasance"), :issued($[{:year(2023)}, {:year(9)}, {:year(14)}]), :note("A deep dive into the forensics of fake references."), :number(42), :publisher("Hu-man Productions"), :title("The Citation Sting: Detecting Academic Malfeasance"), :type("podcast-episode")}),
        :mercurio2026(${:ISBN("978-1-2345-9876-0"), :author($[{:family("Mercurio"), :given("Silvia")},]), :id("mercurio2026"), :issued($[{:month(5), :year(2026)},]), :publisher("Butterfly Press"), :title("The semantic elegance of raku grammars"), :type("book")}),
        :rakudoc-evo-chapter(${
            :ISBN("978-3-16-148410-0"),
            :author($[
                {:family("Hainsworth"), :given("Richard")},
                {:family("Mattijsen"), :given("Elizabeth")},
                {:family("Conway"), :given("Damian")}
            ]),
            :container-title("Modern Markup Systems"),
            :editor($[
                ${:family("Smith"), :given("Jane")}
            ]),
            :id("rakudoc-evo-chapter"),
            :note("Fields can be specified as key => value pairs"),
            :page("42-65"),
            :publisher("Butterfly Press"),
            :publisher-place("Amsterdam"),
            :title("The Evolution of RakuDoc"),
            :type("chapter"),
            issued => { 'date-parts' => [[[2025], [10]]] },
        }),
        :recursive2022phantom(${:DOI("10.0000/meta.ref.2022.01"), :author($[{:family("Réçürsioñ"), :given("Grant")}, {:family("Ghostwriter"), :given("A.")}]), :container-title("Proceedings of the 12th International Conference on Bibliographic Integrity"), :event("ICBI 2022"), :id("recursive2022phantom"), :issued($[{:year(2022)}, {:year(11)}]), :note("Ironically, this paper includes 40 citations that are never mentioned in the body text."), :page("101-105"), :title("Shadow Citations: On the Prevalence and Persistence of Uncited References in Proceeding Metadata"), :type("paper-conference")}), :ref1(${:URL("http://www.ncbi.nlm.nih.gov/pubmed/39876543"), :id("ref1"), :title("The semantic elegance of raku grammars"), :type("book")}), :starlight2024(${:author($[{:family("Starlight"), :given("Orion")},]), :container-title("The Reactive Programmer's Quarterly"), :id("starlight2024"), :issue(4), :issued($[{:month(11), :year(2024)},]), :page("45-60"), :title("Asynchronous Concurrency: A Journey Through Raku Supplies"), :type("article-journal"), :volume(12)}), :thorne2023(${:ISSN("1234-5678"), :author($[{:family("Thorne"), :given("Alistair")},]), :container-title("Journal of Virtual Machine Design"), :id("thorne2023"), :issue("2"), :issued(${:date-parts($[])}), :page("210-235"), :title("Optimization Strategies for MoarVM Bytecode"), :type("article-journal"), :volume("9")}),
        "tlhInganHol:D-1" => ${:ISBN("978-1-2345-6789-0"), :author(${:family("Mercurio"), :given("Silvia")}), :id("Missing-ID-1"), :issued($[{:day("14"), :month("03"), :year("2025")},]), :publisher("Butterfly Press"), :title("The Morphological Beauty of Raku Grammars"), :type("book")},
        "Missing-ID-:yIghun" => ${:URL("https://metacpan.org/pod/Lingua::tlhInganHol::yIghun"), :abstract("Perl module that allows programs to written Klingon syntax and vocabulary."), :accessed($[{:day(25), :month(1), :year(2025)},]), :author(${:family("Conway"), :given("Damian")}), :id("tlhInganHol::yIghun"), :issued($[{:day(1), :month(6), :year(2009)},]), :publisher("MetaCPAN"), :title("Lingua::tlhInganHol::yIghun: Perl code in the original Klingon"), :type("software"), :version("20090601")}, :zenraku2024(${:URL("https://example.org/raku"), :accessed($[{:day(23), :month(1), :year(2026)},]), :author($[{:family("Wall"), :given("Larry")},]), :container-title("Journal of Camel Studies"), :id("zenraku2024"), :issue("3"), :issued($[{:day(12), :month(5), :year(2024)},]), :page("101-115"), :title("The zen of raku"), :type("article-journal"), :volume("42")})
        }
    ),
    :locale("en-GB"),
    :style("acm-siggraph")
}
