# -*- python -*-

# Build the linearity, defect, and crosstalk tables
# This code was adapted from obs_subaru hsc/SConscript

import lsst.sconsUtils
import glob
import os

# scons steals our environment away, so we have to reinstate it
env = lsst.sconsUtils.env.Clone()
for name in ("PYTHONPATH", "LD_LIBRARY_PATH", "DYLD_LIBRARY_PATH", "PATH"):
    if name in os.environ:
        env.AppendENVPath(name, os.environ[name])

# we may need an explicit library load path specified in the command
libpathstr = lsst.sconsUtils.utils.libraryLoaderEnvironment()

# We always run these commands with an explicit python rather than relying on the shebang
python = "{} python".format(libpathstr)

def getLinearizerInFile():
    linearizerInFiles = glob.glob("linearity_table_*.fits")
    if len(linearizerInFiles) == 1:
        return linearizerInFiles[0]

    if len(linearizerInFiles) == 0:
        raise RuntimeError("Could not find a linearity table")
    raise RuntimeError("Found %s linearity tables; need just one" % (len(linearizerInFiles),))

linearizerInFile = getLinearizerInFile()
# I would rather get this from DecamMapper, but could not figure out how to import it
linearizerOutDir = "linearizer"
command = "%s decam/makeLinearizer.py $SOURCE --force" % (python,)

makeLinearizer = env.Command(linearizerOutDir, linearizerInFile, command)


# Ingest defects
pipe_tasks_dir = lsst.sconsUtils.env.ProductDir('pipe_tasks')
data_dir = lsst.sconsUtils.env.ProductDir('obs_decam_data')
command = (f"{python} {pipe_tasks_dir}/bin/ingestCuratedCalibs.py decam/CALIB/ {data_dir}/decam/defects "+
            "--calib decam/CALIB --config clobber=True")
commandInst = env.Command('CALIB/calibRegistry.sqlite3', [], command)
env.Depends(commandInst, lsst.sconsUtils.targets["python"])


# Create crosstalk calibration tables by parsing the ascii table
def getCrosstalkInFile():
    crosstalkInFiles = glob.glob("DECam_xtalk_*.txt")
    if len(crosstalkInFiles) == 1:
        return crosstalkInFiles[0]
    elif len(crosstalkInFiles) == 0:
        raise RuntimeError("Could not find a crosstalk table")
    else:
        raise RuntimeError("Found %s crosstalk tables; need just one" % (len(crosstalkInFiles),))

crosstalkInFile = getCrosstalkInFile()
crosstalkOutDir = "crosstalk"
command = "%s decam/makeCrosstalkDecam.py $SOURCE --force" % (python,)

makeCrosstalk = env.Command(crosstalkOutDir, crosstalkInFile, command)
env.Depends(makeCrosstalk, "makeCrosstalkDecam.py")

# Ingest crosstalk calibration tables into decam/CALIB with
# ingestCuratedCalibs.py so they can be found by butlers using this
# build of obs_decam.
decam_dir = lsst.sconsUtils.env.ProductDir('obs_decam')
command = (f"{python} {pipe_tasks_dir}/bin/ingestCuratedCalibs.py decam/CALIB/ {decam_dir}/decam/crosstalk "+
           "--calib decam/CALIB --config clobber=True")
commandCrosstalkIng = env.Command('CALIB/calibRegistry.sqlite3', [], command)
env.Depends(commandCrosstalkIng, [makeCrosstalk, lsst.sconsUtils.targets["python"]])
