#!perl

use 5.010001;
use strict;
use warnings;
use Log::Any::IfLOG '$log';

use Data::Dmp;
use List::MoreUtils qw(uniq);
use Perinci::CmdLine::Any;

our %SPEC;

sub _uniquify_names {
    my $recs = shift;

    my $names = [map {$_->{name}} @{ $recs }];
    if ((grep {!defined} @$names) || scalar(@{[ uniq(@$names) ]}) < @$names) {
        my $i = -1;
        my %seen;
        for my $rec (@$recs) {
            $i++;
            $rec->{name} //= '';
            if ($seen{ $rec->{name} }++ || $rec->{name} eq '') {
                $rec->{name} .= (length($rec->{name}) ? " " : "") . "#$i";
                # XXX actually still doesn't guarantee unique name
            }
        }
    }
}

$SPEC{bencher} = {
    v => 1.1,
    summary => 'A benchmark framework',
    args => {
        scenario_file => {
            summary => 'Load a scenario from a Perl file',
            description => <<'_',

Perl file will be do()'ed and the last expression should be a hash containing
the scenario specification.

_
            schema => 'str*',
            cmdline_aliases => {f=>{}},
        },
        scenario_module => {
            summary => 'Load a scenario from a Bencher::Scenario:: Perl module',
            description => <<'_',

Will try to load module `Bencher::Scenario::<NAME>` and expect to find a package
variable in the module called `$scenario` which should be a hashref containing
the scenario specification.

_
            schema => ['str*', match=>qr/\A\w+(::\w+)*\z/],
            cmdline_aliases => {m=>{}},
            completion => sub {
                require Complete::Module;
                my %args = @_;
                Complete::Module::complete_module(
                    word=>$args{word}, ns_prefix=>'Bencher::Scenario');
            },
        },
        participants => {
            'summary' => 'Add participants',
            'x.name.is_plural' => 1,
            schema => ['array*', of=>'hash*'],
            cmdline_aliases => {
                p => {
                    summary => 'Add a participant',
                    code => sub {
                        require JSON;

                        my $args = shift;
                        push @{ $args->{participants} },
                            JSON::decode_json($_[0]);
                    },
                }
            },
        },
        datasets => {
            summary => 'Add datasets',
            'x.name.is_plural' => 1,
            schema => ['array*', of=>'hash*'],
            cmdline_aliases => {
                d => {
                    summary => 'Add a dataset',
                    code => sub {
                        require JSON;

                        my $args = shift;
                        push @{ $args->{datasets} },
                            JSON::decode_json($_[0]);
                    },
                },
            },
        },
        action => {
            schema => ['str*', {
                in=>[qw/
                           list-scenario-modules
                           show-scenario
                           list-participants
                           list-participant-modules
                           list-datasets
                           list-items
                           bench
                       /]
                    # list-functions
            }],
            default => 'bench',
            cmdline_aliases => {
                a => {},
                list_scenario_modules => {
                    is_flag => 1,
                    summary => 'Shortcut for -a list-scenario-modules',
                    code => sub { $_[0]{action} = 'list-scenario-modules' },
                },
                L => {
                    is_flag => 1,
                    summary => 'Shortcut for -a list-scenario-modules',
                    code => sub { $_[0]{action} = 'list-scenario-modules' },
                },
                show_scenario => {
                    is_flag => 1,
                    summary => 'Shortcut for -a show-scenario',
                    code => sub { $_[0]{action} = 'show-scenario' },
                },
                list_participants => {
                    is_flag => 1,
                    summary => 'Shortcut for -a list-participants',
                    code => sub { $_[0]{action} = 'list-participants' },
                },
                list_participant_modules => {
                    is_flag => 1,
                    summary => 'Shortcut for -a list-participant-modules',
                    code => sub { $_[0]{action} = 'list-participant-modules' },
                },
                list_datasets => {
                    is_flag => 1,
                    summary => 'Shortcut for -a list-datasets',
                    code => sub { $_[0]{action} = 'list-datasets' },
                },
                list_items => {
                    is_flag => 1,
                    summary => 'Shortcut for -a list-items',
                    code => sub { $_[0]{action} = 'list-items' },
                },
            },
        },
        module_startup => {
            schema => ['bool*', is=>1],
            summary => 'Benchmark module startup',
        },
        detail => {
            schema => 'bool*',
            cmdline_aliases => {l=>{}},
        },
        time_unit => {
            schema => ['str*', in=>[qw/s ms/]],
            default => 's',
            cmdline_aliases => {
                ms => {
                    is_flag => 1,
                    code => sub { $_[0]{time_unit} = 'ms' },
                    summary => 'Alias for --time-unit=ms',
                },
            },
        },
        # XXX include_item
        # XXX exclude_item
        # XXX include_participant
        # XXX exclude_participant
        # XXX include_module
        # XXX exclude_module
    },
};
sub bencher {
    use experimental 'smartmatch';

    my %args = @_;

    my $action = $args{action};

    if ($action eq 'list-scenario-modules') {
        require PERLANCAR::Module::List;
        my $mods = PERLANCAR::Module::List::list_modules(
            'Bencher::Scenario::', {list_modules=>1});
        return [200, "OK",
                [map {s/^Bencher::Scenario:://; $_} sort keys %$mods]];
    }

    my $scenario;
    if (defined $args{scenario_file}) {
        $scenario = do $args{scenario_file};
    } elsif (defined $args{scenario_module}) {
        my $m = "Bencher::Scenario::$args{scenario_module}";
        my $mp = $m; $mp =~ s!::!/!g; $mp .= ".pm";
        require $mp;
        no strict 'refs';
        $scenario = ${"$m\::scenario"};
    } else {
        $scenario = {
            participants => [],
        };
    }

    if ($args{participants}) {
        for (@{ $args{participants} }) {
            push @{ $scenario->{participants} }, $_;
        }
    }
    if ($args{datasets}) {
        $scenario->{datasets} //= [];
        for (@{ $args{datasets} }) {
            push @{ $scenario->{datasets} }, $_;
        }
    }

    if ($action eq 'show-scenario') {
        return [200, "OK", $scenario];
    }

    # parse scenario (extract module names, ...)
    my $parsed = {};
    {
        $parsed->{participants} = [];
        $parsed->{modules} = [];
        my $i = -1;
        for my $p0 (@{ $scenario->{participants} }) {
            $i++;
            my $p = { %$p0, seq=>$i };
            $p->{type} //= 'perl_code';
            if ($p->{fcall_template}) {
                if ($p->{fcall_template} =~ /\A
                                             (\w+(?:::\w+)*)
                                             (::|->)
                                             (\w+)/x) {
                    $p->{module}   = $1;
                    $p->{function} = $3;
                }
            }

            if ($p->{module}) {
                push @{ $parsed->{modules} }, $p->{module}
                    unless $p->{module} ~~ @{ $parsed->{modules} };
            }

            # try to come up with a default name for the participant
            unless (defined($p->{name})) {
                if ($p->{type} eq 'command') {
                    my $cmdline = ref($p->{cmdline}) eq 'ARRAY' ?
                        join(" ", $p->{cmdline}) : $p->{cmdline};
                    $p->{name} = substr($cmdline, 0, 12);
                } elsif ($p->{type} eq 'perl_code') {
                    if ($p->{function}) {
                        $p->{name} = ($p->{module} ? "$p->{module}::" : "").
                            $p->{function};
                    }
                }
            }

            push @{ $parsed->{participants} }, $p;
        } # for each participant

        if ($scenario->{datasets}) {
            $parsed->{datasets} = [];
            my $i = -1;
            for my $ds0 (@{ $scenario->{datasets} }) {
                $i++;
                my $ds = { %$ds0, seq=>$i };

                # try to come up with a default name for the dataset
                unless (defined($ds->{name})) {
                    if ($ds->{args}) {
                        $ds->{name} = substr(dmp($ds->{args}), 0, 14);
                    } elsif ($ds->{argv}) {
                        $ds->{name} = substr(dmp($ds->{argv}), 0, 14);
                    }
                }
                push @{ $parsed->{datasets} }, $ds;
            }
        } # for each dataset

        _uniquify_names($parsed->{participants});
        _uniquify_names($parsed->{datasets}) if $parsed->{datasets};
    }

    if ($action eq 'list-datasets') {
        return [200, "OK", undef] unless $parsed->{datasets};
        my @res;
        for my $ds (@{ $parsed->{datasets} }) {
            if ($args{detail}) {
                push @res, {
                    seq      => $ds->{seq},
                    name     => $ds->{name},
                };
            } else {
                push @res, $ds->{name};
            }
        }
        my %resmeta;
        $resmeta{'table.fields'} = [qw/seq name/]
            if $args{detail};
        return [200, "OK", \@res, \%resmeta];
    }

    if ($action eq 'list-participant-modules') {
        return [200, "OK", $parsed->{modules}];
    }

    if ($action eq 'list-participants') {
        my @res;
        for my $p (@{ $parsed->{participants} }) {
            if ($args{detail}) {
                push @res, {
                    seq      => $p->{seq},
                    type     => $p->{type},
                    name     => $p->{name},
                    function => $p->{function},
                    module   => $p->{module},
                };
            } else {
                push @res, $p->{name};
            }
        }
        my %resmeta;
        $resmeta{'table.fields'} = [qw/seq type name function module/]
            if $args{detail};
        return [200, "OK", \@res, \%resmeta];
    }

    # generate benchmark items from participants
    {
        require Permute::Named::Iter;

        $parsed->{items} = [];
        my @permute;

        # XXX allow permutation of perl path
        # XXX allow permutation of module path

        my @participants;
        my @datasets;

        if ($args{module_startup}) {
            return [412, "There are no modules to benchmark the startup of"]
                unless @{$parsed->{modules}};

            # push perl as base-line
            {
                push @participants, {
                    seq  => 0,
                    name => "loading perl (baseline)",
                    type => 'command',
                    cmdline => [$^X, "-e1"],
                };

                my $i = 0;
                for my $mod (@{ $parsed->{modules} }) {
                    $i++;
                    push @participants, {
                        seq  => $i,
                        name => $mod,
                        type => 'command',
                        cmdline => [$^X, "-M$mod", "-e1"],
                    };
                }
            }

            # postprocess result
            $parsed->{after_bench} = sub {
                my %args = @_;
                my $res = $args{result};
                for my $i (reverse 1..$#{$res}) {
                    $res->[$i]{time} -= $res->[0]{time};
                }
                shift @$res;
            };
        } else {
            return [412, "Please load a scenario (-m, -f) or ".
                        "specify at least one participant (-p)"]
                unless @{$parsed->{participants}};
            @participants = @{ $parsed->{participants} };
            @datasets = @{ $parsed->{datasets} } if $parsed->{datasets};
        }

        push @permute, "participant", [0..$#participants];

        if (@datasets) {
            push @permute, "dataset", [0..$#{$parsed->{datasets}}];
        }
        $log->debugf("permute: %s", \@permute);

        my $iter = Permute::Named::Iter::permute_named_iter(@permute);
        my $i = -1;
        while (my $h = $iter->()) {
            $log->tracef("iter returns: %s", $h);
            $i++;
            my $item_name;
            {
                # convert participant's & dataset index to name temporarily, for
                # nicer item name
                my %h = %$h;
                $h{participant} = $participants[$h{participant}]{name};
                $h{dataset} = $datasets[$h{dataset}]{name}
                    if exists $h{dataset};
                my @k = keys %h;
                if (@k == 1) {
                    $item_name = $h{$k[0]};
                } else {
                    $item_name = dmp(\%h);
                }
            }

            my $p = $participants[$h->{participant}];

            my $code;
            if ($p->{type} eq 'command') {
                my @cmd;
                my $shell;
                if (ref($p->{cmdline}) eq 'ARRAY') {
                    @cmd = @{ $p->{cmdline} };
                    $shell = 0;
                } else {
                    @cmd = ($p->{cmdline});
                    $shell = 1;
                }
                $code = sub {
                    if ($shell) {
                        system $cmd[0];
                    } else {
                        system {$cmd[0]} @cmd;
                    }
                };
            } elsif ($p->{type} eq 'perl_code') {
                my $ds;
                $ds = $datasets[$h->{dataset}] if defined($h->{dataset});
                if ($p->{code}) {
                    if ($ds) {
                        if ($ds->{argv}) {
                            $code = sub { $p->{code}->(@{$ds->{argv}}) };
                        } elsif ($ds->{args}) {
                            $code = sub { $p->{code}->(%{$ds->{args}}) };
                        } else {
                            return [400, "Participant #$p->{seq}: No argv/args supplied for code"];
                        }
                    } else {
                        $code = $p->{code};
                    }
                } elsif (my $template = $p->{code_template} || $p->{fcall_template}) {
                    my $template_vars;
                    if ($ds->{args}) {
                        $template_vars = $ds->{args};
                    } elsif ($ds->{argv}) {
                        $template_vars = { map {$_=>$ds->{argv}[$_]}
                                               @{ $ds->{argv} } };
                    } else {
                        warn "Item #$i: participant specifies code_template/fcall_template but there is no args/argv in the dataset #$h->{dataset}\n";
                    }

                    if ($template_vars) {
                        $template =~ s/\<(\w+)\>/dmp($template_vars->{$1})/eg;
                    }
                    my $code_str = "sub { $template }";
                    $log->debugf("Item #%d: code=%s", $i, $code_str);
                    $code = eval $code_str;
                    return [400, "Item #$i: code compile error: $@ (code: $code_str)"] if $@;
                }
            } else {
                return [400, "Unknown participant type '$p->{type}'"];
            }

            push @{ $parsed->{items} }, {
                seq  => $i,
                name => $item_name,
                code => $code,
            };
        }

    } # generate benchmark items

    if ($action eq 'list-items') {
        my @res;
        for my $it (@{ $parsed->{items} }) {
            if ($args{detail}) {
                push @res, {
                    seq      => $it->{seq},
                    name     => $it->{name},
                };
            } else {
                push @res, $it->{name};
            }
        }
        my %resmeta;
        $resmeta{'table.fields'} = [qw/seq name/]
            if $args{detail};
        return [200, "OK", \@res, \%resmeta];
    }

    if ($action eq 'bench') {
        require Benchmark::Dumb;
        require Module::Load;

        for my $mod (@{ $parsed->{modules} }) {
            Module::Load::load($mod);
        }

        my $tres = Benchmark::Dumb::_timethese_guts(
            0,
            {
                map { $_->{seq} => $_->{code} } @{ $parsed->{items} }
            },
            "silent",
        );
        my @res;
        for my $seq (sort {$a<=>$b} keys %$tres) {
            my $it = $parsed->{items}[$seq];
            push @res, {
                seq     => $seq,
                name    => $it->{name},
                time    => $tres->{$seq}{result}{num},
                rate    => 1 / $tres->{$seq}{result}{num},
                samples => $tres->{$seq}{result}{_dbr_nsamples},
                errors  => $tres->{$seq}{result}{errors}[0],
            };
        }

        if ($parsed->{after_bench}) {
            $parsed->{after_bench}->(result => \@res);
        }

        @res = sort {$b->{time} <=> $a->{time}} @res;

        if ($args{time_unit} eq 'ms') {
            for my $res (@res) {
                $res->{time} = sprintf("%10.4fms", $res->{time}*1000);
            }
        }
        my %resmeta;
        $resmeta{'table.fields'} = [qw/seq name time rate samples errors/];
        return [200, "OK", \@res, \%resmeta];
    }

    [304,"No action"];
}

Perinci::CmdLine::Any->new(
    url => '/main/bencher',
    log => 1,
)->run;

# ABSTRACT: A benchmark framework (CLI)
# PODNAME: bencher

__END__

=pod

=encoding UTF-8

=head1 NAME

bencher - A benchmark framework (CLI)

=head1 VERSION

This document describes version 0.01 of bencher (from Perl distribution Bencher), released on 2015-10-08.

=head1 SYNOPSIS

List all scenario modules (Bencher::Scenario::*):

 % bencher --list-scenario-modules
 % bencher -L

Run benchmark from a scenario module:

 % bencher -m Example

Run benchmark from a scenario file:

 % bencher -f scenario.pl

Add participants etc from the command-line instead of using a scenario
file/module:

 % bencher -p '{"fcall_template":"Bar::func"}'

Run module startup overhead benchmark instead of the normal run:

 % bencher -m Example --module-startup

List participants instead of running benchmark:

 % bencher ... --list-participants

List benchmark items instead of running benchmark:

 % bencher ... --list-items

=head1 DESCRIPTION

=head1 OPTIONS

C<*> marks required options.

=head2 Configuration options

=over

=item B<--config-path>=I<filename>

Set path to configuration file.

Can be specified multiple times.

=item B<--config-profile>=I<s>

Set configuration profile to use.

=item B<--no-config>

Do not use any configuration file.

=back

=head2 Environment options

=over

=item B<--no-env>

Do not read environment for default options.

=back

=head2 Logging options

=over

=item B<--debug>

Set log level to debug (note: you also need to set LOG=1 to enable logging, or use DEBUG=1).

=item B<--log-level>=I<s>

Set log level (note: you also need to set LOG=1 to enable logging).

=item B<--quiet>

Set log level to quiet (note: you also need to set LOG=1 to enable logging, or use QUIET=1).

=item B<--trace>

Set log level to trace (note: you also need to set LOG=1 to enable logging, or use TRACE=1).

=item B<--verbose>

Set log level to info (note: you also need to set LOG=1 to enable logging, or use VERBOSE=1).

=back

=head2 Output options

=over

=item B<--format>=I<s>

Choose output format, e.g. json, text.

Default value:

 undef

=item B<--json>

Set output format to json.

=item B<--naked-res>

When outputing as JSON, strip result envelope.

Default value:

 0

By default, when outputing as JSON, the full enveloped result is returned, e.g.:

    [200,"OK",[1,2,3],{"func.extra"=>4}]

The reason is so you can get the status (1st element), status message (2nd
element) as well as result metadata/extra result (4th element) instead of just
the result (3rd element). However, sometimes you want just the result, e.g. when
you want to pipe the result for more post-processing. In this case you can use
`--naked-res` so you just get:

    [1,2,3]


=back

=head2 Other options

=over

=item B<--action>=I<s>, B<-a>

Default value:

 "bench"

Valid values:

 ["list-scenario-modules","show-scenario","list-participants","list-participant-modules","list-datasets","list-items","bench"]

=item B<--datasets-json>=I<s>

Add datasets (JSON-encoded).

See C<--datasets>.

=item B<--datasets>=I<s>

Add datasets.

=item B<--detail>, B<-l>

=item B<--help>, B<-h>, B<-?>

Display help message and exit.

=item B<--list-datasets>

Shortcut for -a list-datasets.

See C<--action>.

=item B<--list-items>

Shortcut for -a list-items.

See C<--action>.

=item B<--list-participant-modules>

Shortcut for -a list-participant-modules.

See C<--action>.

=item B<--list-participants>

Shortcut for -a list-participants.

See C<--action>.

=item B<--list-scenario-modules>

Shortcut for -a list-scenario-modules.

See C<--action>.

=item B<--module-startup>

Benchmark module startup.

=item B<--ms>

Alias for --time-unit=ms.

See C<--time-unit>.

=item B<--participants-json>=I<s>

Add participants (JSON-encoded).

See C<--participants>.

=item B<--participants>=I<s>

Add participants.

=item B<--scenario-file>=I<s>, B<-f>

Load a scenario from a Perl file.

Perl file will be do()'ed and the last expression should be a hash containing
the scenario specification.


=item B<--scenario-module>=I<s>, B<-m>

Load a scenario from a Bencher::Scenario:: Perl module.

Will try to load module `Bencher::Scenario::<NAME>` and expect to find a package
variable in the module called `$scenario` which should be a hashref containing
the scenario specification.


=item B<--show-scenario>

Shortcut for -a show-scenario.

See C<--action>.

=item B<--time-unit>=I<s>

Default value:

 "s"

Valid values:

 ["s","ms"]

=item B<--version>, B<-v>

Display program's version and exit.

=item B<-d>=I<s>

Add a dataset.

See C<--datasets>.

=item B<-L>

Shortcut for -a list-scenario-modules.

See C<--action>.

=item B<-p>=I<s>

Add a participant.

See C<--participants>.

=back

=head1 SEE ALSO

L<Bencher>

=head1 COMPLETION

This script has shell tab completion capability with support for several
shells.

=head2 bash

To activate bash completion for this script, put:

 complete -C bencher bencher

in your bash startup (e.g. C<~/.bashrc>). Your next shell session will then
recognize tab completion for the command. Or, you can also directly execute the
line above in your shell to activate immediately.

It is recommended, however, that you install L<shcompgen> which allows you to
activate completion scripts for several kinds of scripts on multiple shells.
Some CPAN distributions (those that are built with
L<Dist::Zilla::Plugin::GenShellCompletion>) will even automatically enable shell
completion for their included scripts (using C<shcompgen>) at installation time,
so you can immadiately have tab completion.

=head2 tcsh

To activate tcsh completion for this script, put:

 complete bencher 'p/*/`bencher`/'

in your tcsh startup (e.g. C<~/.tcshrc>). Your next shell session will then
recognize tab completion for the command. Or, you can also directly execute the
line above in your shell to activate immediately.

It is also recommended to install C<shcompgen> (see above).

=head2 other shells

For fish and zsh, install C<shcompgen> as described above.

=head1 ENVIRONMENT

=head2 BENCHER_OPT => str

Specify additional command-line options

=head1 CONFIGURATION FILE

This script can read configuration file, which by default is searched at C<~/.config/bencher.conf>, C<~/bencher.conf> or C</etc/bencher.conf> (can be changed by specifying C<--config-path>). All found files will be read and merged.

To disable searching for configuration files, pass C<--no-config>.

Configuration file is in the format of L<IOD>, which is basically INI with some extra features. 

You can put multiple profiles in a single file by using section names like C<[profile=SOMENAME]>. Those sections will only be read if you specify the matching C<--config-profile SOMENAME>.

List of available configuration parameters:

 action (see --action)
 datasets (see --datasets)
 detail (see --detail)
 format (see --format)
 log_level (see --log-level)
 module_startup (see --module-startup)
 naked_res (see --naked-res)
 participants (see --participants)
 scenario_file (see --scenario-file)
 scenario_module (see --scenario-module)
 time_unit (see --time-unit)

=head1 FILES

~/.config/bencher.conf

~/bencher.conf

/etc/bencher.conf

=head1 HOMEPAGE

Please visit the project's homepage at L<https://metacpan.org/release/Bencher>.

=head1 SOURCE

Source repository is at L<https://github.com/perlancar/perl-Bencher>.

=head1 BUGS

Please report any bugs or feature requests on the bugtracker website L<https://rt.cpan.org/Public/Dist/Display.html?Name=Bencher>

When submitting a bug or request, please include a test-file or a
patch to an existing test-file that illustrates the bug or desired
feature.

=head1 AUTHOR

perlancar <perlancar@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2015 by perlancar@cpan.org.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut
