#!/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 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
		       );
my $ipprc = PS::IPP::Config->new(); # IPP configuration
use File::Spec;

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

my ($warp_id, $camera, $dbname, $workdir, $no_update, $no_op);
GetOptions(
    'warp_id|i=s'       => \$warp_id, # Warp identifier
    'camera|c=s'        => \$camera, # Camera name
    'dbname|d=s'        => \$dbname, # Database name
    'workdir|w=s'       => \$workdir, # Working directory, for output files
    '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",
    -exitval => 3,
) unless defined $warp_id
    and defined $camera;

$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 $dvoImageExtract = can_run('dvoImageExtract') or (warn "Can't find dvoImageExtract" 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 => 1);
    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 => 1);
    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 $tessellations = $ipprc->tessellations(); # Hash of defined tessellations
    foreach my $tess_id ( keys %$tessellations ) {
	### Because DVO doesn't use psModules, it doesn't understand Nebulous --- check
	my ($scheme) = $$tessellations{$tess_id} =~ m|^(\S+):|; # The scheme, e.g., file://, path://
	if (defined $scheme and lc($scheme) eq 'neb') {
	    &my_die("Tessellation $tess_id refers to a Nebulous path: $$tessellations{$tess_id}", $warp_id, $PS_EXIT_CONFIG_ERROR);
	}
	
	my $tess_dir = $ipprc->convert_filename_absolute( $$tessellations{$tess_id} ); # Catdir for DVO
	print STDERR "tessellation: $tess_id, $tess_dir\n";
	
	my %unique_skycells = (); # Identified skycells (all unique by virtue of hash property)
	
	if ($astromSource and $astromSource ne 'NULL') {
	    # We have an 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
	    
	    # 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 the imfiles themselves for the WCS
	    foreach my $imfile (@$imfiles) {
		my $astromFile = $imfile->{chip_uri}; # Astrometry file
		my @matchlist = get_overlaps($astromFile, $tess_dir, $astromAccept); # List of overlaps
		extract_overlaps(\@matchlist, $imfile, $astromFile, $tess_id, \@overlaps, \%unique_skycells);
	    }
	}
	
	# Extract the skycells to images, used as warp templates.
	foreach my $skycell_id (keys %unique_skycells) {
	    my $skyDir = caturi($workdir, "tess_" . $tess_id, "sky_" . $skycell_id );
	    my $skyFile = $ipprc->file_prepare( $skycell_id, $skyDir );
	    unless ($ipprc->file_exists( $skyFile )) {
		my $skyFileResolved = $ipprc->file_create( $skyFile ); # Resolved filename, for Nebulous
		my $command = "$dvoImageExtract -D CATDIR $tess_dir $skycell_id -o $skyFileResolved";
		my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
		    run(command => $command, verbose => 1);
		unless ($success) {
		    $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
		    &my_die("Unable to perform dvoImageExtract: $error_code", $warp_id, $error_code);
		}
	    }
	}
    }
} 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";

# 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 => 1);
    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 => 1);
    unless ($success) {
	$error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
	&my_die("Unable to perform dvoImageOverlaps: $error_code", $warp_id, $error_code);
    }
    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";
    } else {
	$entry = $filename;
	print STDERR "entry: $entry\n";
    }

    my @skycells = &select_skycells($entry, @$matches);	# Matching skycells
    my $Nskycells = @skycells;
    printf STDERR "Nskycells: $Nskycells\n";
    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};
	
	$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__
