#!/usr/bin/env perl

# given a skycell and a list of detection ids go find the corresponding rows in the skycal cmfs
# used to backtrack duplicate detections from a single stack that are associated with the same
# PSPS object

use strict;
use warnings;

use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
use Pod::Usage qw( pod2usage );
use File::Basename;

use IPC::Cmd 0.36 qw( can_run run );
use PS::IPP::Metadata::Config;
use PS::IPP::Config 1.01 qw( :standard );
use PS::IPP::PStamp::Job qw( :standard );

my $ipprc =  PS::IPP::Config->new();

my $missing_tools;
my $releasetool = can_run('releasetool') or (warn "Can't find releasetool" and $missing_tools = 1);
my $java = can_run('java') or (warn "Can't find java" and $missing_tools = 1);

if ($missing_tools) {
    warn("Can't find required tools.");
    exit(3);
}

# change this based on where you want to find the stilts jar. 
# default to Bill's copy. The IPP tree has an older version in ippToPsps/jars/
my $home = "/home/panstarrs/bills";
my $stilts = "$java -jar $home/jars/stilts.jar";

my $skycell_id;
my $det_id;
my $release_name = 'SAS.39';
my $columns = "IPP_IDET X_PSF Y_PSF PSF_INST_FLUX KRON_FLUX FLAGS FLAGS2";
my $verbose = 0;

my @det_ids;
GetOptions(
    "skycell|s=s"   => \$skycell_id,
    "det_id|d=s"    => \@det_ids,
    "cols|c=s"      => \$columns,
) or pod2usage( 2 );

die "usage $0 <skycell_id> <det_id>\n" unless defined $skycell_id and scalar @det_ids;

my $command = "$releasetool -listrelstack -release_name $release_name -skycell_id $skycell_id";
my $stacks = runToolAndParse($command, $verbose);

printf "%d stacks found\n", scalar @$stacks if $verbose;

my $first = 1;
my $detectionArg = "";
foreach $det_id (@det_ids) {
    if ($first) {
        $first = 0;
    } else {
        $detectionArg .= "||";
    } 
    $detectionArg .= "IPP_IDET==$det_id";
}
    
    

foreach my $stack (@$stacks) {
    my $stack_id = $stack->{stack_id};
    my $skycal_path_base = $stack->{skycal_path_base};
    my $filter = $stack->{filter};

    my $cmf = "$skycal_path_base.cmf";
    print "$stack_id $filter\n";
    my $filename = basename($cmf);
    my $resolved = $ipprc->file_resolve($cmf);

    my $extra = $columns ? "keepcols \"$columns\"" : "";

    $resolved .= "'#'SkyChip.psf";

    $command = "$stilts tpipe cmd='select $detectionArg;tablename $filename;$extra' in=$resolved";
    $command .= " ofmt=ascii";

    # print "$command\n";
    my $rc = system ($command);
    if ($rc) {
        my $status = $rc >> 8;
        die "$command failed: $rc $status\n";
    }
}

exit 0;
