#!python

from desitarget.mtl import make_ledger, get_mtl_dir, _get_mtl_nside
from desitarget.QA import _parse_tcnames

# ADM this is the upper-limit for memory for mtl._get_mtl_nside()=32.
nproc = 12
# ADM this is the upper-limit for memory for mtl._get_mtl_nside()=16.
# nproc = 8
# ADM retrieve the $MTL_DIR environment variable.
mtldir = get_mtl_dir()
mtlnside = _get_mtl_nside()
# ADM default obsconditions.
obscon = "DARK"

from argparse import ArgumentParser
ap = ArgumentParser(description='Make an initial HEALPixel-split ledger for a Merged Target List based on a directory of targets')
ap.add_argument("targdir",
                help="Full path to a directory containing files of targets that \
                have been partitioned by HEALPixel (i.e. as made by             \
                `select_targets` with the `bundle_files` option).")
ap.add_argument("--dest",
                help="Full path to the output directory to host the ledger. The \
                filename and full directory structure are built on-the-fly from \
                file headers in targdirname. [defaults to {})".format(mtldir),
                default=mtldir)
ap.add_argument("--obscon",
                help="String matching ONE obscondition in the bitmask yaml file \
                (e.g. 'BRIGHT'). Controls priorities when merging targets and   \
                where the ledger is written. [defaults to {})".format(obscon),
                default=obscon)
ap.add_argument("--numproc", type=int,
                help='number of concurrent processes to use [defaults to {}]'.
                format(nproc),
                default=nproc)
ap.add_argument('--healpixels',
                help="HEALPixels corresponding to `nside` (e.g. '6,9,57'). Only \
                write the ledger for targets in these pixels, at the default    \
                nside, which is [{}]".format(mtlnside),
                default=None)
ap.add_argument('--timestamp',
                help="Override the TIMESTAMP created by make_mtl, and use this  \
                time instead",
                default=None)
ap.add_argument('--append', action='store_true',
                help="Append to existing ledgers, instead of writing new ones.  \
                Particularly useful when adding new secondary targets")
ap.add_argument('--tcnames', default=None,
                help="Comma-separated names of target classes to run (e.g. QSO,LGE).")


ns = ap.parse_args()

# ADM parse the list of HEALPixels in which to run.
pixlist = ns.healpixels
if pixlist is not None:
    pixlist = [int(pix) for pix in pixlist.split(',')]

# ADM parse and check the list of target classes to run.
if ns.tcnames is None:
    tcnames = None
else:
    tcnames = _parse_tcnames(tcstring=ns.tcnames, add_all=False)

make_ledger(ns.targdir, ns.dest, pixlist=pixlist, obscon=ns.obscon,
            numproc=ns.numproc, timestamp=ns.timestamp, append=ns.append,
            tcnames=tcnames)
