#!/usr/bin/perl -w

=head2 SYNOPSIS

    pyt Direct::YT::Stat main
    pyt Direct::YT::Stat main:1
    pyt Direct::YT::Stat map:speedup_map

=cut

use strict;
use warnings;

use Carp qw/croak/;
use Getopt::Long;

use Yandex::YT;
use Yandex::YT::Tx;

#my $LOCAL = 0;
my %VARS;
GetOptions(
    "help" => \&usage,
    "debug" => \$Yandex::YT::DEBUG,
    "path=s" => sub {unshift @INC, $_[1];},
    "var=s" => \%VARS,
    #"local" => \$LOCAL,
    ) || usage("Getopt error: $!");

usage("Incorrect number of parameters") if @ARGV != 2;
usage("Incorrect package name: '$ARGV[0]'") if $ARGV[0] !~ /^(\w+(::\w+)*)(.pm)?$/;
my $pack = $1;
my $job = $ARGV[1];

eval "require $pack" or croak "Can't load module '$pack': $@";

Yandex::YT::Tx::tx_start();
if ($job =~ /^map:(\w+)$/) {
    Yandex::YT::do_map(pack => $pack, name => $1, vars => \%VARS);
} elsif ($job =~ /^reduce:(\w+)$/) {
    Yandex::YT::do_reduce(pack => $pack, name => $1, vars => \%VARS);
} elsif ($job =~ /^(\w+)(?:\:([\d\-\,]+))?$/) {
    my ($name, $steps_str) = ($1, $2);
    my $steps = undef;
    if (defined $steps_str && $steps_str ne '') {
        my %steps_hash;
        for my $s (split ',', $steps_str) {
            if ($s =~ /^\d+$/) {
                $steps_hash{$s} = undef;
            } elsif ($s =~ /^(\d+)-(\d+)$/ && $1 <= $2) {
                undef @steps_hash{$1..$2};
            } else {
                croak "incorrect steps: '$steps_str'";
            }
        }
        $steps = [keys %steps_hash];
    }
    Yandex::YT::do_job(pack => $pack, name => $name, step => $steps, vars => \%VARS);
} else {
    croak "Incorrect job definition: '$job'";
}
Yandex::YT::Tx::tx_commit();

sub usage {
    if (@_) {
        print @_, "\n";
    }
    system("pod2text-utf8 $0");
    exit @_ ? 1 : 0;
}
