#!/usr/bin/env perl

use warnings;
use strict;

## report the program and machine
use Sys::Hostname;
my $host = hostname();
print "\n\n";
print "Starting script $0 on $host\n\n";

use vars qw( $VERSION );
$VERSION = '0.01';

use IPC::Cmd 0.36 qw( can_run run );
use PS::IPP::Metadata::Config;
use PS::IPP::Metadata::Stats;
use PS::IPP::Metadata::List qw( parse_md_list );
use File::Temp qw( tempfile );
use File::Spec;
use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
use Pod::Usage qw( pod2usage );

use PS::IPP::Config qw($PS_EXIT_SUCCESS
		       $PS_EXIT_UNKNOWN_ERROR
		       $PS_EXIT_SYS_ERROR
		       $PS_EXIT_CONFIG_ERROR
		       $PS_EXIT_PROG_ERROR
		       $PS_EXIT_DATA_ERROR
		       $PS_EXIT_TIMEOUT_ERROR
		       metadataLookupStr
		       metadataLookupBool
		       caturi
		       file_scheme
		       );

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

my ($warp_id, $camera, $tess_id, $dbname, $verbose, $no_update, $no_op);
GetOptions(
    'warp_id|i=s'       => \$warp_id, # Warp identifier
    'camera|c=s'        => \$camera, # Camera name
    'tess_id=s'         => \$tess_id, # Tessellation identifier
    'dbname|d=s'        => \$dbname, # Database name
    'verbose'           => \$verbose,   # Print to stdout
    'no-update'         => \$no_update,	# Don't update the database?
    'no-op'             => \$no_op, # Don't do any operations
) or pod2usage( 2 );

pod2usage( -msg => "Unknown option: @ARGV", -exitval => 2 ) if @ARGV;
pod2usage(
    -msg => "Required options: --warp_id --camera --tess_id",
    -exitval => 3,
) unless defined $warp_id
    and defined $camera
    and defined $tess_id;

$ipprc->define_camera($camera);

# Look for programs we need
my $missing_tools;
my $warptool = can_run('warptool') or (warn "Can't find warptool" and $missing_tools = 1);
my $dvoImageOverlaps = can_run('dvoImageOverlaps') or (warn "Can't find dvoImageOverlaps" and $missing_tools = 1);
my $ppConfigDump = can_run('ppConfigDump') or (warn "Can't find ppConfigDump" and $missing_tools = 1);
if ($missing_tools) {
    warn("Can't find required tools.");
    exit($PS_EXIT_CONFIG_ERROR); 
}

my $mdcParser = PS::IPP::Metadata::Config->new;	# Parser for metadata config files

# Get list of component imfiles for exposure
my $imfiles;
{
    my $command = "$warptool -imfile -warp_id $warp_id";
    $command .= " -dbname $dbname" if defined $dbname;
    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
	run(command => $command, verbose => $verbose);
    unless ($success) {
	$error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
	&my_die("Unable to perform warptool -imfile: $error_code", $warp_id, $error_code);
    }
    
    my $metadata = $mdcParser->parse(join "", @$stdout_buf) or
	&my_die("Unable to parse metadata config doc", $warp_id, $PS_EXIT_PROG_ERROR);
    $imfiles = parse_md_list($metadata) or 
	&my_die("Unable to parse metadata list", $warp_id, $PS_EXIT_PROG_ERROR);
}

# Where do we get the astrometry source from?
my $astromSource;		# The astrometry source
my $astromAccept;		# Accept the astrometry unconditionally?
my $astromDepth;		# File level of the astrometry source (SPLIT or MEF)?
{
    my $command = "$ppConfigDump -camera $camera -dump-recipe PSWARP -";
    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
	run(command => $command, verbose => $verbose);
    unless ($success) {
	$error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
	&my_die("Unable to perform ppConfigDump: $error_code", $warp_id, $error_code);
    }
    my $metadata = $mdcParser->parse(join "", @$stdout_buf) or
	&my_die("Unable to parse metadata config doc", $warp_id, $PS_EXIT_PROG_ERROR);
    $astromSource = metadataLookupStr($metadata, 'ASTROM.SOURCE');
    $astromAccept = metadataLookupBool($metadata, 'ASTROM.ACCEPT');
    $astromDepth  = metadataLookupStr($metadata, 'ASTROM.DEPTH');
}

# Determine the imfile/skycell overlaps
my @overlaps = ();

unless ($no_op) {
    # Calculate the overlaps between imfiles and skycells

    my $tess_dir = $ipprc->tessellation_catdir( $tess_id ); # Tessellation catdir for DVO
    $tess_dir = $ipprc->convert_filename_absolute( $tess_dir );
	
    my %unique_skycells = (); # Identified skycells (all unique by virtue of hash property)
    
    # XXX this is a bit too hard wired: the concept is that astrometry comes from the MOSAIC vs CHIP output
    if ($astromSource eq 'PSASTRO.OUTPUT.MEF') {
	# We have a MEF astrometry file from psastro
	my $imfile = $imfiles->[0];
	my $camRoot = $imfile->{cam_path_base};
	my $astromFile = $ipprc->filename($astromSource, $camRoot); # Astrometry file
	
	my @matchlist = get_overlaps($astromFile, $tess_dir, $astromAccept); # List of overlaps
	if (! @matchlist) {
	    &my_die("Unable to perform dvoImageOverlaps: missing astrometry", $warp_id, $PS_EXIT_DATA_ERROR);
	}	    
	# Match each of the imfiles to this list
	foreach my $imfile (@$imfiles) {
	    extract_overlaps(\@matchlist, $imfile, $astromFile, $tess_id, \@overlaps, \%unique_skycells);
	}
    } else {
	# We have per-imfile astrometry
	foreach my $imfile (@$imfiles) {
	    my $astromFile;
	    if ($astromSource eq 'PSASTRO.OUTPUT') {
		my $chipRoot = $imfile->{chip_path_base};
		my $classID = $imfile->{class_id};
		$astromFile = $ipprc->filename($astromSource, $chipRoot, $classID); # Astrometry file
	    } else {
		$astromFile = $imfile->{chip_uri}; # Astrometry file
	    }
	    my @matchlist = get_overlaps($astromFile, $tess_dir, $astromAccept); # List of overlaps
	    if (! @matchlist and $verbose) {
		print "skipping $astromFile\n";
	    }	    
	    
	    extract_overlaps(\@matchlist, $imfile, $astromFile, $tess_id, \@overlaps, \%unique_skycells);
	}
    }
} else {
    # create an overlap with an entry for each skycell:imfile match
    foreach my $imfile (@$imfiles) {
	my %overlap = ();
	$overlap{skycell_id} = 'default';
	$overlap{tess_id}    = 'default';
	$overlap{cam_id}     = $imfile->{cam_id};
	$overlap{class_id}   = $imfile->{class_id};
	$overlap{fault}      = $imfile->{fault};
	push @overlaps, \%overlap;
    }
}

# XXX this file needs some additional error checking: if no overlaps are found, we
# keep running this step over and over (a successful warptool -addoverlap prevents 
# successive warptime -imfile from running.

# Generate a MDC file with the overlaps
my ($overlapFile, $overlapName) = tempfile( 'overlaps.wrp' . $warp_id . '.mdc.XXXX', UNLINK => 1 );
print $overlapFile "warpSkyCellMap MULTI\n\n";
foreach my $overlap (@overlaps) {
    print $overlapFile "warpSkyCellMap   METADATA\n";
    print $overlapFile "  warp_id        S32    $warp_id\n";
    print $overlapFile "  skycell_id     STR    $overlap->{skycell_id}\n";
    print $overlapFile "  tess_id        STR    $overlap->{tess_id}\n";
    print $overlapFile "  cam_id         S32    $overlap->{cam_id}\n";
    print $overlapFile "  class_id       STR    $overlap->{class_id}\n";
    print $overlapFile "  fault          S16    $overlap->{fault}\n";
    print $overlapFile "END\n\n";
}
close $overlapFile;

system "cat $overlapName" if $verbose;

# Add the processed file to the database
unless ($no_update) {
    my $command = "$warptool -addoverlap -mapfile $overlapName"; # Command to run warptool
    $command .= " -dbname $dbname" if defined $dbname;
    
    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
	run(command => $command, verbose => $verbose);
    unless ($success) {
	$error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
	warn("Unable to perform warptool -addoverlap: $error_code\n");
	exit($error_code);
    }
}

sub my_die
{
    my $msg = shift;		# Warning message on die
    my $warp_id = shift;	# Warp identifier
    my $exit_code = shift;	# Exit code to add

    warn($msg);

    # No failure option on warptool for this mode, so just die.
    exit $exit_code;
}

# Run dvoImageOverlaps to get the overlaps; return the output
sub get_overlaps
{
    my $filename = shift;	# Filename on which to run dvoImageOverlaps
    my $tess_dir = shift;	# Tessellation directory
    my $accept = shift;		# Do we use the -accept-astrom flag?

    my $command = "$dvoImageOverlaps -D CATDIR $tess_dir " . $ipprc->file_resolve($filename);
    $command .= ' -accept-astrom' if $accept;
    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
	run(command => $command, verbose => $verbose);
    if (!$success) {
	print "Missing astrometry for $filename --- check ASTROM.SOURCE in PSWARP recipe\n";
	return 0;
    }
    return split ('\n', (join "", @$stdout_buf));
}    

# Extract a list of overlaps for an imfile
#
# The command "dvoImageOverlaps -accept-astrom -D CATDIR tessellation (megacam)" returns:
# 729534pa.cmf[ccd00.hdr]  :  skycell.051.fits
# PSASTRO.OUTPUT[CMF.HEAD] : SKYCELL
# [CMF.HEAD] is optionally used for MEF files (SIMPLE or MOSAIC)
sub extract_overlaps
{
    my $matches = shift;	# Reference to list of skycells from dvoImageOverlaps
    my $imfile = shift;		# Imfile information
    my $filename = shift;	# Filename used with dvoImageOverlaps
    my $tess_id = shift;	# Tessellation identifier
    my $overlaps = shift;	# Reference to list of overlaps
    my $unique_skycells = shift; # Reference to hash of found skycells

    # Get rid of the path
    my @dirlist = File::Spec->splitdir( $filename ); # The elements of the full path
    $filename = pop @dirlist;

    # Work out how to identify this imfile in the output
    my $fileLevel = $imfile->{filelevel};
    my $entry;	# How to identify this imfile in the dvoImageOverlaps output
    if ((lc($fileLevel) eq "chip") && (lc($astromDepth) eq "MEF")) {
	my $class_id = $imfile->{class_id};
	my $chipRoot = $ipprc->file_resolve( $imfile->{chip_path_base} );
	my $extname = $ipprc->extname_rule("CMF.HEAD", $class_id); # MEF psastro output
	
	
	$entry = $filename . '\[' . $extname . '\]';
	print STDERR "entry: $entry, class: $class_id, extname: $extname, chiproot: $chipRoot\n" if $verbose;
    } else {
	$entry = $filename;
	print STDERR "entry: $entry\n" if $verbose;
    }

    my @skycells = &select_skycells($entry, @$matches);	# Matching skycells
    my $Nskycells = @skycells;
    printf STDERR "Nskycells: $Nskycells\n" if $verbose;
    foreach my $skycell (@skycells) {
	my %overlap = ();	# Overlap information for warptool
	$overlap{skycell_id} = $skycell;
	$overlap{tess_id}    = $tess_id;
	$overlap{cam_id}     = $imfile->{cam_id};
	$overlap{class_id}   = $imfile->{class_id};
	$overlap{fault}      = $imfile->{fault};
	push @$overlaps, \%overlap;
	
	printf STDERR "overlap: %s : %s , %s\n", $skycell, $imfile->{cam_id}, $imfile->{class_id} if $verbose;
	
	$unique_skycells->{$skycell} = 1;
    }

    return;
}
    
# Find skycells in the list that come from a particular entry
sub select_skycells 
{
    my $entry = shift;		# File+Ext to search for
    my @list = @_;		# List of "File+Ext : skycell"

    my @skycells = ();
    my %unique = ();		# Ensure we only return unique skycells for this entry

    foreach my $line (@list) {
	if ($line =~ m|$entry|) {
	    my ($skycell) = $line =~ m|$entry\S*\s+:\s+(\S+)|;
	    if (not defined $unique{$skycell}) {
		push @skycells, $skycell;
		$unique{$skycell} = 1;
	    }
	}
    }
    return @skycells;
}

END {
    my $status = $?;
    system("sync") == 0
        or die "failed to execute sync: $!" ;
    $? = $status;
}

__END__
