#!/usr/bin/env python

from desitarget.mtl import add_to_ledgers, get_mtl_dir, _get_mtl_nside

# 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='Add new targets to MTL ledger files from a file of targets')
ap.add_argument("targfile",
                help="Full path to a file of targets")
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)

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(',')]

add_to_ledgers(ns.targfile, mtldir=ns.dest, pixlist=pixlist, obscon=ns.obscon,
               numproc=ns.numproc)
