#!/usr/bin/perl

use utf8;
use strict;
use warnings;
use open ':std', ':encoding(UTF-8)';

use JSON::XS;
use FileHandle;
use Capture::Tiny (qw/:all/);
use Text::CSV::Easy(qw/csv_build csv_parse/);

my $awscli = "aws dynamodb query --table-name prod_accounting_statement_export --key-conditions";

my $file   = shift @ARGV || die "list of labels file is required";
my $period = shift @ARGV || die "period_id is required";

my @files;
my $fh = FileHandle->new( $file, 'r' );
while (<$fh>) {
    chomp;
    my ($label) = split ",", $_;
    $label =~ s/\W//g;
    ## next if $label != 32397;
	print "$label ...\n";
    my $cond   = encode_json( { 'user_id_type' => { 'ComparisonOperator' => 'EQ', 'AttributeValueList' => [ { 'S' => "${label}L" } ] } } );
    my $filter = encode_json( { 'period_ids'   => { 'ComparisonOperator' => 'EQ', 'AttributeValueList' => [ { 'S' => $period } ] } } );
    my $cmd    = "$awscli \'$cond\' --query-filter \'$filter\'";
    my ( $stdout, $stderr, $exit ) = capture { system($cmd ) };
    if ($exit) {
        print STDERR "$stderr\n";
    } else {
        eval {
			utf8::encode($stdout);
            my $href = decode_json($stdout);
            if ( scalar $href->{'Items'} ) {
                push @files, map { $_->{'s3_path'}->{'S'} } @{ $href->{'Items'} };
            }
        };
        if ($@) {
            my $err;
        }
    }
}
$fh->close;

map { print "aws s3 rm $_\n" } @files;

__END__
        "user_id_type": {
            "ComparisonOperator": "EQ",
            "AttributeValueList": [ {"S": "32397L"} ]
        }   
    }' \
    --query-filter '{
        "period_ids": {
            "ComparisonOperator": "EQ",
            "AttributeValueList": [ {"S": "$period_id"} ]
        }   
    }'

