### ----------------------------------------------------
### -- Matrix::Client
### -- Licenses: Artistic-2.0
### -- Authors: Matias Linares
### -- File: scripts/load-docs.p6
### ----------------------------------------------------
#!/usr/bin/env perl6
use v6;
use lib <lib>;
use HTTP::UserAgent;
use JSON::Fast;
use Matrix::Client;

sub get-api-docs {
    my $url = "https://matrix.org/docs/api/client-server/json/api-docs.json";
    my $ua = HTTP::UserAgent.new;

    my $res = $ua.get($url);
    die "Cannot get response $res" unless $res.is-success;

    my $data = from-json($res.content);

    my %tags;

    for $data<paths> -> $path {
        $path.kv.map: -> $p, $methods {
            for $methods.kv -> $method, $description {
                for $description<tags> -> $tag {
                    unless %tags{$tag}:exists {
                        %tags{$tag} = Array.new;
                    }
                    %tags{$tag}.push("{$method.uc} - $p");
                }
            }
        }
    }

    %tags
}

sub MAIN(:$spec?) {
    my %tags = get-api-docs;
    my $total = 0;
    my $completed = 0;
    my $implemented-methods = (
        Matrix::Client, Matrix::Client::Room, Matrix::Client::MediaStore
    ).map(*.^methods».candidates).flat.map(
        {
            quietly try { .WHY.Str } or ""
        }).grep(/_matrix/).SetHash;
    say q:to/EOF/;
    # List of implemented endpoints

    This list was generated by the `load-docs.p6` script that gets the data
    from the [api-docs.json](https://matrix.org/docs/api/client-server/json/api-docs.json)
    from matrix.org. This will give you an overview about what's implemented in the library.
    EOF

    for %tags.sort -> $pair {
        my $tag = $pair.key;
        my $methods = $pair.value;
        say qq:to/EOF/;
        ## $tag
        EOF

        for $methods.Seq.sort -> $m {
            my Str $method = $m.trim;
            my $checked = $implemented-methods{$m} ?? "X" !! " ";
            $completed++ if $implemented-methods{$m};
            $total++;

            if $spec {
                $method = $m.subst(/unstable/, $spec)
            }
            say "- [$checked] " ~ $method;
        }
        say "";
    }

    say qq:to/EOF/;

    # Endpoint completion

    {$completed/$total}% - ($completed/$total)
    EOF
}


