#!/usr/bin/perl

=head1 NAME

lookup_mpc - find detections from MPC obs format in current MOPS DB

=head1 SYNOPSIS

lookup_mpc < OBSFILE

  OBSFILE : MPC-formatted observations
  --debug : dump data, don't insert anything
  --help : show this manpage

=head1 DESCRIPTION

=cut


use strict;
use warnings;
use Data::Dumper;
use Getopt::Long;
use Pod::Usage;
use Mail::Send;
use Astro::Time;

# Just a stub for quick debugging.
use PS::MOPS::Lib qw(:all);
use PS::MOPS::MPC;
use PS::MOPS::DC::Instance;
use PS::MOPS::DC::Field;
use PS::MOPS::DC::Tracklet;
use PS::MOPS::DC::DerivedObject;


# Detection statuses.
our $SUBMISSION_PENDING_NEO = 'P';
our $SUBMISSION_PENDING_STD = 'Q';
our $SUBMISSION_NEO = 'S';
our $SUBMISSION_STD = 'T';
our $SUBMISSION_OUTREACH = 'O';

# Start program here.
my $instance_name;
my $debug;
my $help;
GetOptions(
    'instance=s' => \$instance_name,
    debug => \$debug,
    help => \$help,
) or pod2usage(2);
pod2usage(-verbose => 3) if $help;


my $inst = PS::MOPS::DC::Instance->new(DBNAME => $instance_name);
my $dbname = $inst->dbname;
my $logger = $inst->getLogger();
my $dbh = $inst->dbh;

my $sth = $dbh->prepare(<<"SQL") or die $dbh->errstr;
select desig, dbname, tracklet_id from export.mpc_sub where epoch_mjd < 55649
SQL
my %desigs;
$sth->execute() or die $sth->errstr;
my $href;
while ($href = $sth->fetchrow_hashref()) {
    $desigs{$href->{desig}} = $href;
}
$sth->finish;


# Now fetch tracklet digests.
my $k;
foreach $k (sort keys %desigs) {
    my $db = $desigs{$k}->{dbname};
    my $tid = $desigs{$k}->{tracklet_id};
    next unless $db and $tid;
    $desigs{$k}->{digest} = $dbh->selectrow_array("select digest from $db.tracklets where tracklet_id=$tid") or die "couldn't get data for tracklet $db/T$tid\n";
}

# Now generate SQL to fix.
foreach $k (sort keys %desigs) {
    printf <<"SQL", $desigs{$k}->{digest}, $k;
update export.mpc_sub set digest=%f where desig='%s';
SQL
}
