#############
## LOGGING ##
#############
import logging
from astrobase import log_sub, log_fmt, log_date_fmt

DEBUG = False
if DEBUG:
    level = logging.DEBUG
else:
    level = logging.INFO
LOGGER = logging.getLogger(__name__)
logging.basicConfig(
    level=level,
    style=log_sub,
    format=log_fmt,
    datefmt=log_date_fmt,
)

LOGDEBUG = LOGGER.debug
LOGINFO = LOGGER.info
LOGWARNING = LOGGER.warning
LOGERROR = LOGGER.error
LOGEXCEPTION = LOGGER.exception

#############
## IMPORTS ##
#############
import os, subprocess
from copy import deepcopy
from glob import glob

def make_mcmc_vetting_report_page(dirname, append_to_full_report=1):
    """
    Given results of MCMC fitting from fit_models_to_gold, generate a summary
    one-page PDF file.

    If append_to_full_report is True, the summary PDF containing all the
    relevant pages will also be generated by concatenating the existing reports
    with the one-page MCMC summary.

    The bash script version is append_fitgold_results_to_vetting_reports.sh;
    this function ports to python.

    Dependencies:
    * imagemagick `convert`, https://imagemagick.org/index.php
    * pdftk
    """
    assert isinstance(dirname, str)
    assert os.path.exists(dirname)

    vetm_path = glob(os.path.join(dirname, 'vetm_*pdf'))
    if len(vetm_path) > 0:
        LOGINFO(f"Found {vetm_path}")
        return 1

    d = deepcopy(dirname)
    if not d.endswith('/'):
        d += '/'

    bash_command = (
    #
    # First, convert the PDF table to an image, and trim out the white space.
    #
    f"convert -density 300 {d}*posteriortable.pdf -quality 100 -alpha remove {d}tempposteriortable.png; "+
    f"convert {d}tempposteriortable.png -bordercolor white -border 2x2 -trim +repage {d}temptrimmed.png; "+
    f"convert {d}temptrimmed.png -resize 1971x {d}temptrimmedresized.png; "+
    #
    # Next, generate the individual panels to be used
    #
    # Panel 1 (top): light curves.
    f"convert {d}*rawlc.png -resize 1971x {d}temprawlc.png; "+
    f"convert {d}*rawtrimlc.png -resize 1971x {d}temprawtrimlc.png; "+
    f"convert {d}temprawlc.png {d}temprawtrimlc.png +append {d}1.png; "+
    # Panel 2 (bottom): phase plot, posterior table, and corner plot.
    f"convert {d}*cornerplot.png -resize 1971x {d}tempcorner.png; "+
    f"convert {d}*phaseplot.png -resize 1971x {d}tempphaseplot.png; "+
    f"convert {d}tempphaseplot.png {d}temptrimmedresized.png -append {d}left.png; "+
    f"convert {d}left.png {d}tempcorner.png +append {d}2.png; "+
    f"rm {d}temp*png {d}left.png; "+
    # Create the new pdf page to append!
    f"convert {d}1.png {d}2.png -append {d}page.png; "+
    f"convert {d}page.png -units pixelsperinch -density 131.4 +repage {d}mcmc_page.pdf; "
    f"rm {d}1.png {d}2.png {d}page.png; "
    )

    cwd = os.getcwd()
    LOGINFO(f"Running {bash_command}")
    proc = subprocess.run(
        bash_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
        shell=True
    )

    if append_to_full_report:
        # Append the new MCMC vetting page to the full vetting report!

        # e.g., hlsp_cdips_tess_ffi_gaiatwo0000542223510700499968-0025-cam4-ccd4_tess_v01_llc
        basename = os.path.basename(d[:-1])
        assert basename.startswith('hlsp_')
        assert basename.endswith('_llc')

        # identify the "vet_hlsp_cdips_tess_ffi_gaiatwo0000542223510700499968-0025-cam4-ccd4_tess_v01_llc.pdf" analog to
        # which we will append the new page.
        srcpaths = glob( os.path.join(
            '/Users/luke/Dropbox/proj/cdips/results/vetting_classifications/Sector14_through_Sector26', 'collab_*PC*',
            f"*{basename}*"
        ))
        assert len(srcpaths) == 1, 'Expected one match.'
        srcpath = srcpaths[0]

        # "m" for "medium", or "mcmc".  we just want a string to distinguish the two.
        dstpath = os.path.join(
            d,
            os.path.basename(srcpath).replace('vet_','vetm_')
        )

        bash_command = (
            f"pdftk {srcpath} {d}mcmc_page.pdf output {dstpath}"
        )

        LOGINFO(f"Running {bash_command}")
        proc = subprocess.run(
            bash_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
            shell=True
        )

        assert os.path.exists(dstpath)
