#!/usr/bin/env python
#####################################################################################
# (c) Copyright 1998-2023 CERN for the benefit of the LHCb and ATLAS collaborations #
#                                                                                   #
# This software is distributed under the terms of the Apache version 2 licence,     #
# copied verbatim in the file "LICENSE".                                            #
#                                                                                   #
# In applying this licence, CERN does not waive the privileges and immunities       #
# granted to it by virtue of its status as an Intergovernmental Organization        #
# or submit itself to any jurisdiction.                                             #
#####################################################################################

import os
import shutil
import sys
import xml.parsers.expat
from subprocess import Popen

from GaudiProfiling.GenerateGaudiOpts import ConvertXmlToDict

if __name__ == "__main__":
    from PyCPUFamily import CPUFamily

    if "ENV_PROJECT_SOURCE_DIR" not in os.environ:
        print(
            """
            ****************************************** ERROR *****************************************
            * GaudiProfiler: Environment variable $ENV_PROJECT_SOURCE_DIR is missing. Process stopped. *
            ******************************************************************************************
        """
        )
        sys.exit()
    if "GAUDIPROFILERCONFIG" in os.environ:
        configFile = os.environ["GAUDIPROFILERCONFIG"]
    else:
        configFile = os.path.sep.join(
            [
                os.environ["ENV_PROJECT_SOURCE_DIR"],
                "GaudiProfiling",
                "data",
                "pfm_config_%s.xml" % CPUFamily(),
            ]
        )
    try:
        conf = ConvertXmlToDict(configFile)
    except xml.parsers.expat.ExpatError:
        print("Invalid xml file: %s" % configFile)
        sys.exit()
    # gaudiRunParams = ' '.join(sys.argv[1:])
    storeResultsAt = conf.PFM_CONFIG.PROPERTIES.OUTPUT_DIR
    startAtEvent = conf.PFM_CONFIG.CONFIG.START_AT_EVENT
    family = conf.PFM_CONFIG.PROCESSOR.FAMILY
    moduleName = "GaudiProfiling.GenerateGaudiOpts"
    if not os.path.exists(storeResultsAt):
        os.makedirs(storeResultsAt)
    tmpc = 1
    for es in conf.PFM_CONFIG.EVENTS.EVENT_SET:
        tmpc += 1
        counter = []
        cmask = []
        invmask = []
        sampling_period = []
        if not isinstance(es.EVENT, list):
            es.EVENT = [es.EVENT]
        for x in range(len(es.EVENT)):
            counter.append(es.EVENT[x].NAME)
            cmask.append(es.EVENT[x].CMASK)
            invmask.append(es.EVENT[x].INVMASK)
            sampling_period.append(es.EVENT[x].SMPL_PERIOD)  # os.getcwd()
        res = Popen(
            ["gaudirun.py"]
            + sys.argv[1:]
            + [
                "--option",
                "from %s import generateOptions; generateOptions(%s, %s, %s, %s, %s, %r, %r)"
                % (
                    moduleName,
                    counter,
                    cmask,
                    invmask,
                    sampling_period,
                    startAtEvent,
                    storeResultsAt,
                    family,
                ),
            ]
        ).wait()
        if res:
            print(
                """
            ************************************** ERROR ***************************************
            * GaudiProfiler: PerfMonAuditor failed. Is pfm library and kernel patch installed? *
            ************************************************************************************
            """
            )
            sys.exit(res)
    # post-processing
    os.system("GaudiGenProfilingHtml.exe %s --caa" % storeResultsAt)
    shutil.copy2(
        os.path.sep.join(
            [
                os.environ["ENV_PROJECT_SOURCE_DIR"],
                "GaudiProfiling",
                "data",
                "sorttable.js",
            ]
        ),
        os.path.sep.join([storeResultsAt, "HTML"]),
    )
    print("Results:", os.path.sep.join([storeResultsAt, "HTML", "index.html"]))
