#!perl

our $DATE = '2015-10-11'; # DATE
our $VERSION = '0.03'; # VERSION

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
            }
        }
    }
}

sub _find_record_by_seq {
    my ($recs, $seq) = @_;

    for my $rec (@$recs) {
        return $rec if $rec->{seq} == $seq;
    }
    undef;
}

sub _filter_records_by_name_or_seq {
    my %args = @_;

    my $recs = $args{records};
    my $include = $args{include};
    my $exclude = $args{exclude};
    my $include_pattern = $args{include_pattern};
    my $exclude_pattern = $args{exclude_pattern};

    my $frecs = [];

  REC:
    for my $rec (@$recs) {
        if ($include && @$include) {
            my $included;
          INC:
            for my $inc (@$include) {
                if ($inc =~ /\A\d+\z/) {
                    if ($rec->{seq} == $inc) {
                        $included++;
                        last INC;
                    }
                } else {
                    if ($rec->{name} eq $inc) {
                        $included++;
                        last INC;
                    }
                }
            }
            next REC unless $included;
        }
        if ($exclude && @$exclude) {
            for my $exc (@$exclude) {
                if ($exc =~ /\A\d+\z/) {
                    next REC if $rec->{seq} == $exc;
                } else {
                    next REC if $rec->{name} eq $exc;
                }
            }
        }
        if ($include_pattern) {
            next REC unless $rec->{seq} =~ /$include_pattern/i ||
                $rec->{name} =~ /$include_pattern/i;
        }
        if ($exclude_pattern) {
            next REC if $rec->{seq} =~ /$exclude_pattern/i ||
                $rec->{name} =~ /$exclude_pattern/i;
        }
        push @$frecs, $rec;
    }

    $frecs;
}

sub _get_scenario {
    my %args = @_;

    my $pargs = $args{parent_args};

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

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

# parse scenario (extract module names, filter modules, ...)
sub _parse_scenario {
    use experimental 'smartmatch';

    my %args = @_;

    my $unparsed = $args{scenario};
    my $pargs = $args{parent_args};

    my $parsed = {};

    $parsed->{participants} = [];
    $parsed->{on_failure} = $unparsed->{on_failure};
    $parsed->{modules} = [];
    my $i = -1;
    for my $p0 (@{ $unparsed->{participants} }) {
        $i++;
        my $p = { %$p0, seq=>$i };
        $p->{type} //= do {
            if ($p->{cmdline}) {
                'command';
            } else {
                '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};
                } elsif ($p->{module}) {
                    $p->{name} = $p->{module};
                }
            }
        }

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

    if ($unparsed->{datasets}) {
        $parsed->{datasets} = [];
        my $i = -1;
        for my $ds0 (@{ $unparsed->{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};

    # filter by include_modules & exclude_modules
    if ($pargs->{include_modules} && @{ $pargs->{include_modules} }) {
        $parsed->{modules} = [grep {
            $_ ~~ @{ $pargs->{include_modules} }
        } @{ $parsed->{modules} }];
        $parsed->{participants} = [grep {
            !defined($_->{module}) || $_->{module} ~~ @{ $pargs->{include_modules} }
        } @{ $parsed->{participants} }];
    }
    if ($pargs->{exclude_modules} && @{ $pargs->{exclude_modules} }) {
        $parsed->{modules} = [grep {
            !($_ ~~ @{ $pargs->{exclude_modules} })
        } @{ $parsed->{modules} }];
        $parsed->{participants} = [grep {
            !defined($_->{module}) || !($_->{module} ~~ @{ $pargs->{exclude_modules} })
        } @{ $parsed->{participants} }];
    }
    if ($pargs->{include_module_pattern}) {
        $parsed->{modules} = [grep {
            $_ =~ qr/$pargs->{include_module_pattern}/i
        } @{ $parsed->{modules} }];
        $parsed->{participants} = [grep {
            !defined($_->{module}) || $_->{module} =~ qr/$pargs->{include_module_pattern}/i
        } @{ $parsed->{participants} }];
    }
    if ($pargs->{exclude_module_pattern}) {
        $parsed->{modules} = [grep {
            $_ !~ qr/$pargs->{exclude_module_pattern}/i
        } @{ $parsed->{modules} }];
        $parsed->{participants} = [grep {
            !defined($_->{module}) || $_->{module} !~ qr/$pargs->{exclude_module_pattern}/i
        } @{ $parsed->{participants} }];
    }

    $parsed->{participants} = _filter_records_by_name_or_seq(
        records => $parsed->{participants},
        include => $pargs->{include_participants},
        exclude => $pargs->{exclude_participants},
        include_pattern => $pargs->{include_participant_pattern},
        exclude_pattern => $pargs->{exclude_participant_pattern},
    );
    $parsed->{datasets} = _filter_records_by_name_or_seq(
        records => $parsed->{datasets},
        include => $pargs->{include_datasets},
        exclude => $pargs->{exclude_datasets},
        include_pattern => $pargs->{include_dataset_pattern},
        exclude_pattern => $pargs->{exclude_dataset_pattern},
    );

    $parsed;
}

sub _gen_items {
    require Permute::Named::Iter;

    my %args = @_;

    my $parsed = $args{scenario};
    my $pargs  = $args{parent_args};

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

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

    my $participants;
    my $datasets;

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

        {
            # push perl as base-line
            push @$participants, {
                seq  => 0,
                name => "perl -e1 (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"],
                };
            }
        }
    } 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", [map {$_->{seq}} @$participants];

    if ($datasets) {
        push @permute, "dataset", [map {$_->{seq}} @$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;

        my $p = _find_record_by_seq($participants, $h->{participant});
        my $ds; $ds = _find_record_by_seq($datasets, $h->{dataset})
            if exists $h->{dataset};

        {
            # convert participant's & dataset index to name temporarily, for
            # nicer item name
            my %h = %$h;
            $h{participant} = $p->{name};
            $h{dataset} = $ds->{name} if $ds;
            my @k = keys %h;
            if (@k == 1) {
                $item_name = $h{$k[0]};
            } else {
                $item_name = dmp(\%h);
            }
        }

        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;
                }
                die "Command failed (child error=$?, os error=$!)\n"
                    if $?;
            };
        } elsif ($p->{type} eq 'perl_code') {
            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}, dataset #$h->{dataset}: 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,
        };
    }

    $parsed->{items} = _filter_records_by_name_or_seq(
        records => $parsed->{items},
        include => $pargs->{include_items},
        exclude => $pargs->{exclude_items},
        include_pattern => $pargs->{include_item_pattern},
        exclude_pattern => $pargs->{exclude_item_pattern},
    );
    [200];
}

sub _complete_module {
    my %args = @_;
    my $word    = $args{word} // '';
    my $cmdline = $args{cmdline};
    my $r       = $args{r};

    return undef unless $cmdline;

    # force reading config file
    $r->{read_config} = 1;
    my $res = $cmdline->parse_argv($r);

    my $args = $res->[2];
    my $unparsed = _get_scenario(parent_args=>$args);
    my $parsed = _parse_scenario(scenario=>$unparsed, parent_args=>$args);

    require Complete::Util;
    Complete::Util::complete_array_elem(
        word  => $word,
        array => $parsed->{modules},
    );
}

sub _complete_participant {
    my %args = @_;
    my $word    = $args{word} // '';
    my $cmdline = $args{cmdline};
    my $r       = $args{r};

    return undef unless $cmdline;

    # force reading config file
    $r->{read_config} = 1;
    my $res = $cmdline->parse_argv($r);

    my $args = $res->[2];
    my $unparsed = _get_scenario(parent_args=>$args);
    my $parsed = _parse_scenario(scenario=>$unparsed, parent_args=>$args);

    require Complete::Util;
    Complete::Util::complete_array_elem(
        word  => $word,
        array => [map {($_->{seq}, $_->{name})} @{$parsed->{participants}}],
    );
}

sub _complete_dataset {
    my %args = @_;
    my $word    = $args{word} // '';
    my $cmdline = $args{cmdline};
    my $r       = $args{r};

    return undef unless $cmdline;

    # force reading config file
    $r->{read_config} = 1;
    my $res = $cmdline->parse_argv($r);

    my $args = $res->[2];
    my $unparsed = _get_scenario(parent_args=>$args);
    my $parsed = _parse_scenario(scenario=>$unparsed, parent_args=>$args);

    require Complete::Util;
    Complete::Util::complete_array_elem(
        word  => $word,
        array => [map {($_->{seq}, $_->{name})} @{$parsed->{datasets}}],
    );
}

sub _complete_item {
    my %args = @_;
    my $word    = $args{word} // '';
    my $cmdline = $args{cmdline};
    my $r       = $args{r};

    return undef unless $cmdline;

    # force reading config file
    $r->{read_config} = 1;
    my $res = $cmdline->parse_argv($r);

    my $args = $res->[2];
    my $unparsed = _get_scenario(parent_args=>$args);
    my $parsed = _parse_scenario(scenario=>$unparsed, parent_args=>$args);
    $res = _gen_items(scenario=>$parsed, parent_args=>$args);
    return undef unless $res->[0] == 200;

    require Complete::Util;
    Complete::Util::complete_array_elem(
        word  => $word,
        array => [grep {!/\{/} # remove names that are too unwieldy
                      map {($_->{seq}, $_->{name})} @{$parsed->{items}}],
    );
}

$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' },
                },
            },
            tags => ['category:action'],
        },
        module_startup => {
            schema => ['bool*', is=>1],
            summary => 'Benchmark module startup overhead instead of normal benchmark',
            tags => ['category:action'],
        },
        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',
                },
            },
        },

        include_modules => {
            'x.name.is_plural' => 1,
            summary => 'Only include modules specified in this list',
            'summary.alt.plurality.singular' => 'Add module to include list',
            schema => ['array*', of=>'str*'],
            element_completion => \&_complete_module,
            tags => ['category:filtering'],
        },
        include_module_pattern => {
            summary => 'Only include modules matching this regex pattern',
            schema => ['re*'],
            tags => ['category:filtering'],
        },
        exclude_modules => {
            'x.name.is_plural' => 1,
            summary => 'Exclude modules specified in this list',
            'summary.alt.plurality.singular' => 'Add module to exclude list',
            schema => ['array*', of=>'str*'],
            element_completion => \&_complete_module,
            tags => ['category:filtering'],
        },
        exclude_module_pattern => {
            summary => 'Exclude module(s) matching this regex pattern',
            schema => ['re*'],
            tags => ['category:filtering'],
        },

        include_participants => {
            'x.name.is_plural' => 1,
            summary => 'Only include participants whose seq/name matches this',
            'summary.alt.plurality.singular' => 'Add participant to include list',
            schema => ['array*', of=>'str*'],
            element_completion => \&_complete_participant,
            tags => ['category:filtering'],
        },
        include_participant_pattern => {
            summary => 'Only include participants matching this regex pattern',
            schema => ['re*'],
            tags => ['category:filtering'],
        },
        exclude_participants => {
            'x.name.is_plural' => 1,
            summary => 'Exclude participants whose seq/name matches this',
            'summary.alt.plurality.singular' => 'Add participant to include list',
            schema => ['array*', of=>'str*'],
            element_completion => \&_complete_participant,
            tags => ['category:filtering'],
        },
        exclude_participant_pattern => {
            summary => 'Exclude participants matching this regex pattern',
            schema => ['re*'],
            tags => ['category:filtering'],
        },

        include_items => {
            'x.name.is_plural' => 1,
            summary => 'Only include items whose seq/name matches this',
            'summary.alt.plurality.singular' => 'Add item to include list',
            schema => ['array*', of=>'str*'],
            element_completion => \&_complete_item,
            tags => ['category:filtering'],
        },
        include_item_pattern => {
            summary => 'Only include items matching this regex pattern',
            schema => ['re*'],
            tags => ['category:filtering'],
        },
        exclude_items => {
            'x.name.is_plural' => 1,
            summary => 'Exclude items whose seq/name matches this',
            'summary.alt.plurality.singular' => 'Add item to exclude list',
            schema => ['array*', of=>'str*'],
            element_completion => \&_complete_item,
            tags => ['category:filtering'],
        },
        exclude_item_pattern => {
            summary => 'Exclude items matching this regex pattern',
            schema => ['re*'],
            tags => ['category:filtering'],
        },

        include_datasets => {
            'x.name.is_plural' => 1,
            summary => 'Only include datasets whose seq/name matches this',
            'summary.alt.plurality.singular' => 'Add dataset to include list',
            schema => ['array*', of=>'str*'],
            element_completion => \&_complete_dataset,
            tags => ['category:filtering'],
        },
        include_dataset_pattern => {
            summary => 'Only include datasets matching this regex pattern',
            schema => 're*',
            tags => ['category:filtering'],
        },
        exclude_datasets => {
            'x.name.is_plural' => 1,
            summary => 'Exclude datasets whose seq/name matches this',
            'summary.alt.plurality.singular' => 'Add dataset to exclude list',
            schema => ['array*', of=>'str*'],
            element_completion => \&_complete_dataset,
            tags => ['category:filtering'],
        },
        exclude_dataset_pattern => {
            summary => 'Exclude datasets matching this regex pattern',
            schema => 're*',
            tags => ['category:filtering'],
        },

        on_failure => {
            summary => "What to do when command fails or Perl code dies",
            schema => ['str*', in=>[qw/die skip/]],
            description => <<'_',

The default is "die". When set to "skip", will first run the code of each item
before benchmarking and trap command failure/Perl exception and if that happens,
will "skip" the item.

_
        },
    },
};
sub bencher {
    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, recurse=>1});
        return [200, "OK",
                [map {s/^Bencher::Scenario:://; $_} sort keys %$mods]];
    }

    my $unparsed = _get_scenario(parent_args=>\%args);

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

    my $parsed = _parse_scenario(scenario=>$unparsed, parent_args=>\%args);

    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},
                    cmdline  => ref($p->{cmdline}) eq 'ARRAY' ? join(" ", @{$p->{cmdline}}) : $p->{cmdline},
                };
            } else {
                push @res, $p->{name};
            }
        }
        my %resmeta;
        $resmeta{'table.fields'} = [qw/seq type name module function cmdline/]
            if $args{detail};
        return [200, "OK", \@res, \%resmeta];
    }

    my $res = _gen_items(scenario=>$parsed, parent_args=>\%args);
    return $res unless $res->[0] == 200;

    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 $on_failure = $args{on_failure} // $parsed->{on_failure} // 'die';
        if ($on_failure eq 'skip') {
            my $fitems = [];
            for my $it (@{ $parsed->{items} }) {
                eval { $it->{code}->() };
                if ($@) {
                    warn "Skipping item #$it->{seq} ($it->{name}) ".
                        "due to failure\n";
                    next;
                }
                push @$fitems, $it;
            }
            $parsed->{items} = $fitems;
        }

        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 rate time 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.03 of bencher (from Perl distribution Bencher), released on 2015-10-11.

=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 Action 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<--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 overhead instead of normal benchmark.

=item B<--show-scenario>

Shortcut for -a show-scenario.

See C<--action>.

=item B<-L>

Shortcut for -a list-scenario-modules.

See C<--action>.

=back

=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 Filtering options

=over

=item B<--exclude-dataset-pattern>=I<s>

Exclude datasets matching this regex pattern.

=item B<--exclude-dataset>=I<s@>

Add dataset to exclude list.

Can be specified multiple times.

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

Exclude datasets whose seq/name matches this (JSON-encoded).

See C<--exclude-dataset>.

=item B<--exclude-item-pattern>=I<s>

Exclude items matching this regex pattern.

=item B<--exclude-item>=I<s@>

Add item to exclude list.

Can be specified multiple times.

=item B<--exclude-items-json>=I<s>

Exclude items whose seq/name matches this (JSON-encoded).

See C<--exclude-item>.

=item B<--exclude-module-pattern>=I<s>

Exclude module(s) matching this regex pattern.

=item B<--exclude-module>=I<s@>

Add module to exclude list.

Can be specified multiple times.

=item B<--exclude-modules-json>=I<s>

Exclude modules specified in this list (JSON-encoded).

See C<--exclude-module>.

=item B<--exclude-participant-pattern>=I<s>

Exclude participants matching this regex pattern.

=item B<--exclude-participant>=I<s@>

Add participant to include list.

Can be specified multiple times.

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

Exclude participants whose seq/name matches this (JSON-encoded).

See C<--exclude-participant>.

=item B<--include-dataset-pattern>=I<s>

Only include datasets matching this regex pattern.

=item B<--include-dataset>=I<s@>

Add dataset to include list.

Can be specified multiple times.

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

Only include datasets whose seq/name matches this (JSON-encoded).

See C<--include-dataset>.

=item B<--include-item-pattern>=I<s>

Only include items matching this regex pattern.

=item B<--include-item>=I<s@>

Add item to include list.

Can be specified multiple times.

=item B<--include-items-json>=I<s>

Only include items whose seq/name matches this (JSON-encoded).

See C<--include-item>.

=item B<--include-module-pattern>=I<s>

Only include modules matching this regex pattern.

=item B<--include-module>=I<s@>

Add module to include list.

Can be specified multiple times.

=item B<--include-modules-json>=I<s>

Only include modules specified in this list (JSON-encoded).

See C<--include-module>.

=item B<--include-participant-pattern>=I<s>

Only include participants matching this regex pattern.

=item B<--include-participant>=I<s@>

Add participant to include list.

Can be specified multiple times.

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

Only include participants whose seq/name matches this (JSON-encoded).

See C<--include-participant>.

=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<--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<--ms>

Alias for --time-unit=ms.

See C<--time-unit>.

=item B<--on-failure>=I<s>

What to do when command fails or Perl code dies.

Valid values:

 ["die","skip"]

The default is "die". When set to "skip", will first run the code of each item
before benchmarking and trap command failure/Perl exception and if that happens,
will "skip" the item.


=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<--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<-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)
 exclude_dataset_pattern (see --exclude-dataset-pattern)
 exclude_datasets (see --exclude-dataset)
 exclude_item_pattern (see --exclude-item-pattern)
 exclude_items (see --exclude-item)
 exclude_module_pattern (see --exclude-module-pattern)
 exclude_modules (see --exclude-module)
 exclude_participant_pattern (see --exclude-participant-pattern)
 exclude_participants (see --exclude-participant)
 format (see --format)
 include_dataset_pattern (see --include-dataset-pattern)
 include_datasets (see --include-dataset)
 include_item_pattern (see --include-item-pattern)
 include_items (see --include-item)
 include_module_pattern (see --include-module-pattern)
 include_modules (see --include-module)
 include_participant_pattern (see --include-participant-pattern)
 include_participants (see --include-participant)
 log_level (see --log-level)
 module_startup (see --module-startup)
 naked_res (see --naked-res)
 on_failure (see --on-failure)
 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
