#!/usr/bin/env python

from desitarget.mtl import loop_ledger, check_archiving
from desiutil.log import get_logger
log = get_logger()

# ADM default survey to run.
survey = "main"

from argparse import ArgumentParser
ap = ArgumentParser(description='Update ledgers for the Merged Target based on new spectroscopic observations')
ap.add_argument("obscon",
                help="String matching ONE obscondition in the bitmask yaml file \
                (e.g. 'BRIGHT'). Controls priorities when merging targets, which\
                tiles to process, etc.", choices=["DARK", "BRIGHT", "BACKUP",
                                                  "DARK1B", "BRIGHT1B"])
ap.add_argument("-s", "--survey",
                help="Flavor of survey to run. Defaults to [{}]".format(survey),
                default=survey, choices=["main", "sv3", "sv2"])
ap.add_argument('--zcatdir',
                help="Full path to the directory that hosts the redshift        \
                catalogs. Default is to use the $ZCAT_DIR environment variable",
                default=None)
ap.add_argument('--mtldir',
                help="Full path to the directory that hosts the MTL ledgers.    \
                Default is to use the $MTL_DIR environment variable",
                default=None)
ap.add_argument("-nosec", "--nosecondary", action='store_true',
                help="By default, we always process the ledger of secondaries   \
                in addition to the primaries so they keep pace. Pass this if    \
                there are no secondaries to process")
ap.add_argument("--reprocess", action='store_true',
                help="Run reprocessed tiles (instead of the standard loop)")
ap.add_argument("--noarchivecheck", action='store_true',
                help="Do NOT check if tiles-specstatus and archived tiles match")
ap.add_argument("--noveto", action='store_true',
                help="Do NOT veto targets using files in the veto directory")

ns = ap.parse_args()

veto = not(ns.noveto)

if not ns.noarchivecheck:
    check_archiving(ns.obscon, survey=ns.survey, zcatdir=ns.zcatdir,
                    mtldir=ns.mtldir)

scndstates = [False]

# ADM if nosecondary wasn't passed, also process the secondary ledger
# ADM for programs that actually have secondary ledgers (BRIGHT/DARK).
if ns.obscon in ["BRIGHT", "DARK", "BRIGHT1B", "DARK1B"]:
    if not(ns.nosecondary):
        scndstates = [True, False]

premsg = ["Processed", "REprocessed"][ns.reprocess]

# ADM for the DESI extension (1B) first use the redshifts on the 1B tiles
# ADM to update the Main Survey ledgers.
if "1B" in ns.obscon:
    obscon = ns.obscon.split("1B")[0]
    loop_ledger(
        obscon, survey='main', zcatdir=ns.zcatdir, mtldir=ns.mtldir,
        secondary=False, reprocess=ns.reprocess, ext=True, veto=veto)

for secondary in scndstates:
    # ADM run through the regular loop once.
    hpdirname, mtltilefn, tilefn, tiles = loop_ledger(
        ns.obscon, survey=ns.survey, zcatdir=ns.zcatdir, mtldir=ns.mtldir,
        secondary=secondary, reprocess=ns.reprocess, veto=veto)

    log.info("MTL ledger directory: {}".format(hpdirname))
    log.info("MTL tile file: {}".format(mtltilefn))
    log.info("Redshift tile file: {}".format(tilefn))
    log.info("{} {} tiles, which are: {}".format(premsg, len(tiles), tiles))
