#!perl

## no critic: (InputOutput::ProhibitReadlineInForLoop)

use 5.010001;
use strict 'subs', 'vars';
use warnings;
use Log::ger;

use Complete::Util qw(arrayify_answer);
use Getopt::Long::More;
use Sort::Sub ();

our $AUTHORITY = 'cpan:PERLANCAR'; # AUTHORITY
our $DATE = '2025-01-13'; # DATE
our $DIST = 'App-subsort'; # DIST
our $VERSION = '0.052'; # VERSION

my %opts = (
    chomp => 1,
    ignore_case => 0,
    reverse => 0,
    key => undef,
    input_record_separator => "\n",
    output_record_separator => "",
);
my ($routine, $meta);
my $routine_args = {};
my @files;
my $res = GetOptions(
    'ignore_case|f' => sub { $opts{ignore_case} = 1 },
    'reverse|r'     => sub { $opts{reverse} = 1 },
    'key|k=s'       => \$opts{key},
    'no-chomp|C'    => sub { $opts{chomp} = 0 },
    '0:s'           => sub {
        if (!defined($_[1]) || $_[1] eq '') {
            $opts{input_record_separator}  = "\0";
        } elsif ($_[1] =~ /\A[0-7]{3}\z/) {
            $opts{input_record_separator} = chr(oct($_[1]));
        } elsif ($_[1] =~ /\Ax[0-9A-Fa-f]{2}\z/) {
            $opts{input_record_separator} = chr(hex($_[1]));
        } else {
            warn "Invalid record separator (-0), please specify octal e.g. -0177 or hexadecimal e.g. -0x7f";
            die "";
        }
    },
    'para' => sub {
        $opts{input_record_separator} = "";
        #$opts{output_record_separator} = "\n\n";
    },
    'help|h'        => sub {
        print <<'TEXT';
sortsub - Sort lines of text using Sort::Sub routines

Usage:
  % subsort [OPTIONS] <ROUTINE> [FILE]...
  % subsort --help (or -h)
  % subsort --list (or -l)
  % subsort --version (or -v)

Examples:

 # sort by length, in descending order
 % subsort by_length -r < data
 % subsort 'by_length<r>' < data

Options:
  --help, -h         Show this help message and exit.
  --version, -v      Show version and exit.
  --list, -l         List available Sort::Sub routines.

  --no-chomp, -C     Don't chomp newlines (input record separator) from input
                       and don't re-add newlines (output record separator) when
                       printing.
  --ignore-case, -f  Do a case-insensitive sort.
  --reverse, -r      Do a reverse sort.
  --arg=s, -A        Argument to pass to sorter. In the form of name=val. Can
                       be specified multiple times.
  -0[octal or hexa]  Specify record separator character (default is newline).
  --para             Split input per paragraph (by blank lines).
  --key=s, -k        Perl code to generate sort key to sort against.

TEXT
        exit 0;
    },
    'version|v'     => sub {
        no warnings 'once';
        say "subsort version ", ($main::VERSION // 'dev'),
            " (", ($main::DATE // 'no date'), ")";
        exit 0;
    },
    'list|l'        => sub {
        require Module::List::Tiny;
        my $mods = Module::List::Tiny::list_modules(
            "Sort::Sub::", {list_modules=>1});
        for (sort keys %$mods) {
            s/.+:://;
            say $_;
        }
        exit 0;
    },
    '<>' => optspec(
        destination => sub {
            my $val = shift;
            if (!defined $routine) {
                $routine = $val;
            } else {
                push @files, $val;
            }
        },
        completion => sub {
            my %args = @_;
            if ($args{argpos} == 0) {
                require Complete::Module;
                Complete::Module::complete_module(
                    word => $args{word},
                    ns_prefix => "Sort::Sub",
                );
            } else {
                require Complete::File;
                Complete::File::complete_file(
                    word => $args{word},
                );
            }
        },
    ),
    'arg|A=s' => optspec(
        destination => sub {
            my $val = $_[1];
            die "subsort: Invalid syntax in --arg (-A), please use name=val: $val\n"
                unless $val =~ /(.+?)=(.*)/;
            $routine_args->{$1} = $2;
        },
        completion => sub {
            require Complete::Sequence;
            my %args = @_;

            my $compres;

            # do we have the routine already? if yes, extract the metadata
            my $rname;
            {
                $rname = $routine;
                last if defined $rname;
                $rname = $args{words}[0] if @{ $args{words} };
            }
            return [] unless defined $rname;

            my $mod = "Sort::Sub::$rname";
            (my $mod_pm = "$mod.pm") =~ s!::!/!g;
            eval { require $mod_pm };
            return {message=>"Cannot load $mod: $@"} if $@;
            my $meta;
            eval { $meta = $mod->meta };
            return [] unless $meta;

            return Complete::Sequence::complete_sequence(
                word => $args{word},
                sequence => [
                    sub {
                        [$meta->{args} ? keys(%{ $meta->{args} }) : ()];
                    },
                    '=',
                    sub {
                        my $stash = shift;
                        my $argname = $stash->{completed_item_words}[0];
                        return [] unless defined $argname;

                        my $argspec = $meta->{args}{$argname};
                        return [] unless $argspec->{schema};

                        require Complete::Sah;
                        arrayify_answer(
                            Complete::Sah::complete_from_schema(
                                word => $stash->{cur_word},
                                schema => $argspec->{schema},
                            )
                        );

                    },
                ],
            );

          RETURN_COMPRES:
            return $compres;
        }, # completion for 'arg'
    ),
);
exit 1 unless $res;

die "subsort: Please specify routine to use\n" unless defined $routine;
$routine =~ s/-/_/g; # ux

($routine, $meta) = Sort::Sub::get_sorter(
    "$routine".
        ($routine =~ /</ ? '' :
         "<".($opts{ignore_case} ? "i":"").($opts{reverse} ? "r":"").">"),
    $routine_args,
    "with meta",
);
@ARGV = @files;
local $/ = $opts{input_record_separator};
local $\ = $opts{output_record_separator};
#say "D:output_record_separator = <$opts{output_record_separator}>";
if (defined $opts{key}) {
    my $code_gen_key = eval "sub { $opts{key} }";
    die "Can't compile code in --key: $@" if $@;
    my @lines = map {$_} <>;
    if ($opts{chomp}) { chomp @lines }
    my @keys; for (@lines) { push @keys, $code_gen_key->($_) }
    my @sorted_indices = sort {
        local $main::a = $keys[$a];
        local $main::b = $keys[$b];
        if ($meta->{compares_record}) {
            $main::a = [$main::a, $_];
            $main::b = [$main::b, $_];
        }
        my $res = $routine->($main::a, $main::b);
        log_trace "Comparing keys %s and %s: %d",
            $main::a, $main::b, $res;
        $res;
    } 0..$#lines;

    if ($opts{chomp}) {
        say   $lines[$_] for @sorted_indices;
    } else {
        print $lines[$_] for @sorted_indices;
    }

} else {
    my $i = 0;
    for (sort {
        my $res;
        if ($meta->{compares_record}) {
            $res = $routine->($main::a, $main::b);
            log_trace "Comparing data records %s and %s: %d",
                $main::a, $main::b, $res;
        } else {
            $res = $routine->($main::a->[0], $main::b->[0]);
            log_trace "Comparing data items %s and %s: %d",
                $main::a->[0], $main::b->[0], $res;
        }
        $res;
    } map { if ($opts{chomp}) { chomp; [$_, $i++] } else { [$_, $i++] } } <>) {
        if ($opts{chomp}) {
            say $_->[0];
        } else {
            print $_->[0];
        }
    }
}

# ABSTRACT: Sort lines of text (or records) using Sort::Sub routines
# PODNAME: subsort

__END__

=pod

=encoding UTF-8

=head1 NAME

subsort - Sort lines of text (or records) using Sort::Sub routines

=head1 VERSION

This document describes version 0.052 of subsort (from Perl distribution App-subsort), released on 2025-01-13.

=head1 SYNOPSIS

 % subsort [OPTIONS] <ROUTINE> [FILE]...

Examples:

 % subsort naturally data.txt
 % subsort naturally -r data.txt
 % subsort 'naturally<r>' data.txt
 % some-cmd | subsort by_several -A first='by_length<r>' -A second=numerically data.txt

Some other examples:

 # like Unix's tac
 % subsort record-by-reverse-order data.txt

To list all available routines:

 % subsort -l

=head1 DESCRIPTION

This program is like the Unix command B<sort>, but it uses routines from
L<Sort::Sub>.

=head1 TIPS AND TRICKS

=head2 Debugging

If you use `--key`, you can use L<Log::ger::Screen> to check the resulting keys,
e.g.:

 % some-command-that-produces-lines | PERL5OPT=-MLog::ger::Screen TRACE=1 subsort numerically --key '/(\d+)/; $1 // 0'

=head2 Sorting by multiple criteria

The L<Sort::Sub> routine C<by_several> (L<Sort::Sub::by_several>) allows you to
sort by multiple sort subroutines. For example:

 % some-command-that-produces-lines | subsort by_several -A first=numerically -A second=randomly

=head1 OPTIONS

  --help, -h         Show this help message and exit.
  --version, -v      Show version and exit.
  --list, -l         List available Sort::Sub routines.

  --ignore-case, -f  Do a case-insensitive sort.
  --reverse, -r      Do a reverse sort.
  --arg=s, -A        Argument to pass to sorter. In the form of name=val. Can
                       be specified multiple times.
  --key=s, -k        Perl code to generate sort key to sort against.
  -0[octal or hexa]  Specify record separator character (default is newline).
  --para             Split input per paragraph (by blank lines).

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

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 modules using L<cpanm-shcompgen>
which can activate shell completion for scripts immediately.

=head2 tcsh

To activate tcsh completion for this script, put:

 complete subsort 'p/*/`subsort`/'

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 HOMEPAGE

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

=head1 SOURCE

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

=head1 SEE ALSO

The B<sort> Unix command.

L<App::psort>

L<Sort::Sub>, which also provides sorting functionality to various other CLI's
e.g. L<sorted> (from L<App::sorted>)).

=head1 AUTHOR

perlancar <perlancar@cpan.org>

=head1 CONTRIBUTING


To contribute, you can send patches by email/via RT, or send pull requests on
GitHub.

Most of the time, you don't need to build the distribution yourself. You can
simply modify the code, then test via:

 % prove -l

If you want to build the distribution (e.g. to try to install it locally on your
system), you can install L<Dist::Zilla>,
L<Dist::Zilla::PluginBundle::Author::PERLANCAR>,
L<Pod::Weaver::PluginBundle::Author::PERLANCAR>, and sometimes one or two other
Dist::Zilla- and/or Pod::Weaver plugins. Any additional steps required beyond
that are considered a bug and can be reported to me.

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2025 by perlancar <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.

=head1 BUGS

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

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.

=cut