#! /usr/bin/env python3

import sys
import os 
from importlib.machinery import SourceFileLoader
import types
import argparse

# make the behaviour of 'cmsRun file.py' and 'edmConfigDump file.py' more consistent
sys.path.append(os.getcwd())

parser = argparse.ArgumentParser(description="Expand python configuration")
parser.add_argument("filename",
                    help="Python configuration file")
parser.add_argument("--prune", action="store_true",
                    help="Prune the configuration before printing it")
parser.add_argument("--pruneVerbose", action="store_true",
                    help="With --prune, be verbose on what is pruned")
parser.add_argument("-o", "--output", type=str, default=None,
                    help="Save the configuration dump into this file. In this case any printouts from the configuration continue to be printed to stdout. Default is to print the configuration dump to stdout.")

options = parser.parse_args()
handle = open(options.filename, 'r')
loader=SourceFileLoader("pycfg", options.filename)
mod=types.ModuleType(loader.name)
loader.exec_module(mod)
cmsProcess= mod.process

if options.prune:
    cmsProcess.prune(options.pruneVerbose)

if options.output is not None:
    with open(options.output, "w") as f:
        f.write(cmsProcess.dumpPython())
else:
    print(cmsProcess.dumpPython())

