#!perl

our $DATE = '2017-12-11'; # DATE
our $VERSION = '0.111'; # VERSION

use 5.010;
use strict;
use warnings;

use Perinci::CmdLine::Any;

our %SPEC;

$SPEC{wrap_with_perinci_sub_wrapper} = {
    v => 1.1,
    summary => 'Wrap subroutine with Perinci::Sub::Wrapper',
    description => <<'_',

This script is useful for testing Perinci::Sub::Wrapper. You specify input Rinci
metadata either using `--meta` or using `--url` to get it from Riap URL.

You then can show the code generated by the wrapper using `--show-code` (`-c`).

Or, you can call the wrapped function with one or more sets of arguments, by
supplying `--code` and one of: `--args`, `--multiple-args`, `--args-file`, or
`--multiple-args-file`.

_
    args_rels => {
        'req_one&' => [
            [qw/meta url/],
        ],
        # XXX code is not required if user uses url
        'choose_one&' => [
            [qw/args args_file multiple_args multiple_args_file/],
        ],
        # XXX: args, multiple_args, args_file, multiple_args_file only required if none of
        #'req_dep_any&' => [
        #    [],
        #],
    },
    args => {
        meta => {
            summary => 'Specify function metadata',
            schema => 'hash*',
            pos => 0,
            tags => ['category:meta-specification'],
        },
        url => {
            schema => 'str*',
            summary => 'Use function metadata from Riap URL',
            tags => ['category:meta-specification'],
        },
        # meta_file?
        code => {
            summary => 'Specify Perl code to wrap',
            schema => 'str*',
            tags => ['category:code-specification'],
        },

        args => {
            schema => ['hash*'],
            pos => 1,
            tags => ['category:argument-specification'],
        },
        multiple_args => {
            summary => 'Call with multiple args (array of args)',
            schema => ['array*', of=>'any'],
            tags => ['category:argument-specification'],
        },
        args_file => {
            schema => 'str*',
            summary => 'Retrieve args from file',
            description => <<'_',

JSON and YAML formats are supported. File type will be guessed from filename,
defaults to JSON.

_
            'x.schema.entity' => 'filename',
            tags => ['category:argument-specification'],
        },
        multiple_args_file => {
            schema => 'str*',
            summary => 'Retrieve multiple args from file',
            description => <<'_',

This is like `args_file` except that for multiple args. Content must be an
array.

_
            'x.schema.entity' => 'filename',
            tags => ['category:argument-specification'],
        },
        args_file_type => {
            schema => ['str*', in=>[qw/json yaml/]],
            summary => 'Give hint for args file type',
            tags => ['category:argument-specification'],
        },

        wrap => {
            schema => ['bool*', is=>1],
            default => 1,
            tags => ['category:wrapping'],
        },

        show_meta => {
            summary => "Don't call sub or wrap, show normalized metadata (before wrapping) only",
            schema => ['bool', is=>1],
            tags => ['category:action-selection'],
        },
        show_wrap_meta => {
            summary => "Don't call sub, show generated metadata after wrapping only",
            schema => ['bool', is=>1],
            tags => ['category:action-selection'],
        },
        show_wrap_code => {
            summary => "Don't call sub, show generated wrapper code only",
            schema => ['bool', is=>1],
            cmdline_aliases => {c=>{}},
            tags => ['category:action-selection'],
        },
        args_with_result => {
            summary => "Show args alongside with call result",
            description => <<'_',

The default is to show the call result only.

_
            schema => ['bool', is=>1],
            cmdline_aliases => {d=>{}},
            tags => ['category:output'],
        },
        with_debug => {
            summary => 'Generate wrapper with debug on',
            description => <<'_',

This means e.g. to pepper the wrapper code with more comments.

_
            schema => ['bool', is=>1],
            tags => ['category:wrapping'],
        },
        validate_args => {
            schema => ['bool'],
            default => 1,
            tags => ['category:wrapping'],
        },
        validate_result => {
            schema => ['bool'],
            default => 1,
            tags => ['category:wrapping'],
        },
        core => {
            summary => 'Whether to generate code which avoids the use of non-core modules',
            schema => ['bool'],
            tags => ['category:wrapping'],
        },
        core_or_pp => {
            summary => 'Whether to generate code which avoids the use of non-core XS modules',
            schema => ['bool'],
            description => <<'_',

In other words, generated code should stick with core or pure-perl modules.

_
            tags => ['category:wrapping'],
        },
        pp => {
            summary => 'Whether to generate code which avoids the use of XS modules',
            schema => ['bool'],
            tags => ['category:wrapping'],
        },

        linenum => {
            summary => 'When showing source code (--show-wrap-code), add line numbers',
            schema => ['bool', is=>1],
            cmdline_aliases => {l=>{}},
            tags => ['category:output'],
        },
    },
    examples => [
    ],
};
sub wrap_with_perinci_sub_wrapper {
    my %args = @_;

    my $code;
    if ($args{code}) {
        $code = eval "sub { $args{code} }";
    }

    my $meta;
    if (defined $args{meta}) {
        $meta = $args{meta};
    } elsif (defined $args{url}) {
        require Perinci::Access;
        my $pa = Perinci::Access->new;
        my $res = $pa->request(meta => $args{url});
        return $res unless $res->[0] == 200;
        $meta = $res->[2];

        if (!$code &&
                $args{url} =~ m!^(?:pl:)?/((?:[^/]+)(?:/[^/]+)*)/([^/]+)!) {
            no strict 'refs';
            my ($mod, $func) = ($1, $2);
            require "$mod.pm";
            $mod =~ s!/!::!g;
            $code //= \&{"$mod\::$func"};
        }
    }

    if ($args{show_meta}) {
        require Perinci::Sub::Normalize;
        return [200, "OK",
                Perinci::Sub::Normalize::normalize_function_metadata($meta)];
    }

  WRAP:
    {
        last unless $args{wrap};
        require Perinci::Sub::Wrapper;

        my %wrap_opts;
        {
            $wrap_opts{validate_args}   = $args{validate_args};
            $wrap_opts{validate_result} = $args{validate_result};
            $wrap_opts{debug}           = $args{with_debug};
            $wrap_opts{compile}         = 0 if $args{show_wrap_code};
            $wrap_opts{meta}            = $meta;
            $wrap_opts{sub}             = $code // sub {[200]};
            $wrap_opts{core}            = 1 if $args{core};
            $wrap_opts{core_or_pp}      = 1 if $args{core_or_pp};
            $wrap_opts{pp}              = 1 if $args{pp};
        }

        my $res = Perinci::Sub::Wrapper::wrap_sub(%wrap_opts);

        return $res unless $res->[0] == 200;

        $meta = $res->[2]{meta};

        if ($args{show_wrap_meta}) {
            require Data::Dump;
            return [200, "OK", Data::Dump::dump($meta),
                    {'cmdline.skip_format'=>1}];
        }

        if ($args{show_wrap_code}) {
            my $source = $res->[2]{source};
            $source .= "\n" unless $source =~ /\R\z/;
            if ($args{linenum}) {
                require String::LineNumber;
                $source = String::LineNumber::linenum($source);
            }
            return [200, "OK", $source, {'cmdline.skip_format'=>1}];
        }

        $code = $res->[2]{sub};
    }

    my $args;
    my $multiple;
    if (exists $args{args}) {
        $args = $args{args};
    } elsif ($args{multiple_args}) {
        $args = $args{multiple_args};
        $multiple = 1;
    } elsif (defined($args{args_file}) || defined($args{multiple_args_file})) {
        my $path;
        if (defined $args{args_file}) {
            $path = $args{args_file};
        } else {
            $path = $args{multiple_args_file};
            $multiple = 1;
        }
        my $type = $args{args_file_type};
        if (!$type) {
            if ($path =~ /\b(json)$/i) { $type = 'json' }
            elsif ($path =~ /\b(yaml|yml)$/i) { $type = 'yaml' }
            else { $type = 'json' }
        }
        if ($type eq 'json') {
            require File::Slurper;
            require JSON::MaybeXS;
            my $ct = File::Slurper::read_text($path);
            $args = JSON::MaybeXS->new->allow_nonref->decode($ct);
        } elsif ($type eq 'yaml') {
            require YAML::XS;
            $args = YAML::XS::LoadFile($path);
        } else {
            return [400, "Unknown args file type '$type', please specify json/yaml"];
        }
    } else {
        return [400, "Please specify 'args' or 'multiple_args' or 'args_file' or 'multiple_args_file'"];
    }
    if ($multiple) {
        return [400, "Multiple args must be an array"] unless ref($args) eq 'ARRAY';
    } else {
        return [400, "args must be a hash"] unless ref($args) eq 'HASH';
    }

    if ($multiple) {
        if ($args{args_with_result}) {
            return [200, "OK", [map {{args=>%$_, result=>$code->($_)}} @$args]];
        } else {
            return [200, "OK", [map {$code->(%$_)} @$args]];
        }
    } else {
        if ($args{args_with_result}) {
            return [200, "OK", {args=>$args, result=>$code->(%$args)}];
        } else {
            return [200, "OK", $code->(%$args)];
        }
    }

    [500, "BUG: This should not be reached"];
}

my $cli = Perinci::CmdLine::Any->new(
    url => '/main/wrap_with_perinci_sub_wrapper',
);
$cli->{common_opts}{naked_res}{default} = 1;
$cli->run;

# ABSTRACT: Wrap subroutine with Perinci::Sub::Wrapper
# PODNAME: wrap-with-perinci-sub-wrapper

__END__

=pod

=encoding UTF-8

=head1 NAME

wrap-with-perinci-sub-wrapper - Wrap subroutine with Perinci::Sub::Wrapper

=head1 VERSION

This document describes version 0.111 of wrap-with-perinci-sub-wrapper (from Perl distribution App-PerinciUtils), released on 2017-12-11.

=head1 SYNOPSIS

Usage:

 % wrap-with-perinci-sub-wrapper [options] [meta] [args]

=head1 DESCRIPTION

This script is useful for testing Perinci::Sub::Wrapper. You specify input Rinci
metadata either using C<--meta> or using C<--url> to get it from Riap URL.

You then can show the code generated by the wrapper using C<--show-code> (C<-c>).

Or, you can call the wrapped function with one or more sets of arguments, by
supplying C<--code> and one of: C<--args>, C<--multiple-args>, C<--args-file>, or
C<--multiple-args-file>.

=head1 OPTIONS

C<*> marks required options.

=head2 Action selection options

=over

=item B<--show-meta>

Don't call sub or wrap, show normalized metadata (before wrapping) only.

=item B<--show-wrap-code>, B<-c>

Don't call sub, show generated wrapper code only.

=item B<--show-wrap-meta>

Don't call sub, show generated metadata after wrapping only.

=back

=head2 Argument specification options

=over

=item B<--args-file-type>=I<s>

Give hint for args file type.

Valid values:

 ["json","yaml"]

=item B<--args-file>=I<filename>

Retrieve args from file.

JSON and YAML formats are supported. File type will be guessed from filename,
defaults to JSON.


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

See C<--args>.

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

=item B<--multiple-args-file>=I<filename>

Retrieve multiple args from file.

This is like `args_file` except that for multiple args. Content must be an
array.


=item B<--multiple-args-json>=I<s>

Call with multiple args (array of args) (JSON-encoded).

See C<--multiple-args>.

=item B<--multiple-args>=I<s>

Call with multiple args (array of args).

=back

=head2 Code specification options

=over

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

Specify Perl code to wrap.

=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 Meta specification options

=over

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

Specify function metadata (JSON-encoded).

See C<--meta>.

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

Specify function metadata.

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

Use function metadata from Riap URL.

=back

=head2 Output options

=over

=item B<--args-with-result>, B<-d>

Show args alongside with call result.

The default is to show the call result only.


=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<--linenum>, B<-l>

When showing source code (--show-wrap-code), add line numbers.

=item B<--no-naked-res>

When outputing as JSON, add result envelope.

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 Wrapping options

=over

=item B<--core>

Whether to generate code which avoids the use of non-core modules.

=item B<--core-or-pp>

Whether to generate code which avoids the use of non-core XS modules.

In other words, generated code should stick with core or pure-perl modules.


=item B<--no-validate-args>

=item B<--no-validate-result>

=item B<--pp>

Whether to generate code which avoids the use of XS modules.

=item B<--with-debug>

Generate wrapper with debug on.

This means e.g. to pepper the wrapper code with more comments.


=item B<--wrap>

=back

=head2 Other options

=over

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

Display help message and exit.

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

Display program's version and exit.

=back

=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 wrap-with-perinci-sub-wrapper wrap-with-perinci-sub-wrapper

in your bash startup (e.g. F<~/.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 modules using L<cpanm-shcompgen>
which can activate shell completion for scripts immediately.

=head2 tcsh

To activate tcsh completion for this script, put:

 complete wrap-with-perinci-sub-wrapper 'p/*/`wrap-with-perinci-sub-wrapper`/'

in your tcsh startup (e.g. F<~/.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 L<shcompgen> (see above).

=head2 other shells

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

=head1 CONFIGURATION FILE

This script can read configuration files. Configuration files are in the format of L<IOD>, which is basically INI with some extra features.

By default, these names are searched for configuration filenames (can be changed using C<--config-path>): F<~/.config/wrap-with-perinci-sub-wrapper.conf>, F<~/wrap-with-perinci-sub-wrapper.conf>, or F</etc/wrap-with-perinci-sub-wrapper.conf>.

All found files will be read and merged.

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

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

You can also put configuration for multiple programs inside a single file, and use filter C<program=NAME> in section names, e.g. C<[program=NAME ...]> or C<[SOMESECTION program=NAME]>. The section will then only be used when the reading program matches.

Finally, you can filter a section by environment variable using the filter C<env=CONDITION> in section names. For example if you only want a section to be read if a certain environment variable is true: C<[env=SOMEVAR ...]> or C<[SOMESECTION env=SOMEVAR ...]>. If you only want a section to be read when the value of an environment variable has value equals something: C<[env=HOSTNAME=blink ...]> or C<[SOMESECTION env=HOSTNAME=blink ...]>. If you only want a section to be read when the value of an environment variable does not equal something: C<[env=HOSTNAME!=blink ...]> or C<[SOMESECTION env=HOSTNAME!=blink ...]>. If you only want a section to be read when an environment variable contains something: C<[env=HOSTNAME*=server ...]> or C<[SOMESECTION env=HOSTNAME*=server ...]>. Note that currently due to simplistic parsing, there must not be any whitespace in the value being compared because it marks the beginning of a new section filter or section name.

List of available configuration parameters:

 args (see --args)
 args_file (see --args-file)
 args_file_type (see --args-file-type)
 args_with_result (see --args-with-result)
 code (see --code)
 core (see --core)
 core_or_pp (see --core-or-pp)
 format (see --format)
 linenum (see --linenum)
 meta (see --meta)
 multiple_args (see --multiple-args)
 multiple_args_file (see --multiple-args-file)
 naked_res (see --naked-res)
 pp (see --pp)
 show_meta (see --show-meta)
 show_wrap_code (see --show-wrap-code)
 show_wrap_meta (see --show-wrap-meta)
 url (see --url)
 validate_args (see --no-validate-args)
 validate_result (see --no-validate-result)
 with_debug (see --with-debug)
 wrap (see --wrap)

=head1 ENVIRONMENT

=head2 WRAP_WITH_PERINCI_SUB_WRAPPER_OPT => str

Specify additional command-line options.

=head1 FILES

F<~/.config/wrap-with-perinci-sub-wrapper.conf>

F<~/wrap-with-perinci-sub-wrapper.conf>

F</etc/wrap-with-perinci-sub-wrapper.conf>

=head1 HOMEPAGE

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

=head1 SOURCE

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

=head1 BUGS

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

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) 2017, 2016, 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
