#! /bin/env python

from argparse import ArgumentParser
from RecoBTag.CTagging.helpers import get_vars
import os
import FWCore.ParameterSet.Config as cms
import hashlib
from pdb import set_trace

parser = ArgumentParser('''This script produces the CMSSW configuration to provide to the Charm Tagging discriminators.
WARNING: It automatically overwrites the official CMSSW file in the proper location! Use git commands to restore previous settings. ''')
parser.add_argument('CvsLXML', help='XML Weight file of the Charm vs Light training')
parser.add_argument('CvsBXML', help='XML Weight file of the Charm vs B training')
args = parser.parse_args()

if not os.path.isfile(args.CvsLXML):
   raise ValueError('File %s does not exists!' % args.CvsLXML)
if not os.path.isfile(args.CvsBXML):
   raise ValueError('File %s does not exists!' % args.CvsBXML)

with open(args.CvsLXML) as CvsLXML:
   sha1_CvsLXML = hashlib.sha1(CvsLXML.read()).hexdigest()

with open(args.CvsBXML) as CvsBXML:
   sha1_CvsBXML = hashlib.sha1(CvsBXML.read()).hexdigest()

CvsLXML_vpset = cms.VPSet(
   *get_vars(args.CvsLXML, False) #False: do not mimick FileInPath functionalities and take the bare path as the file path
    )
CvsBXML_vpset = cms.VPSet(
   *get_vars(args.CvsBXML, False)
    )

with open('%s/src/RecoBTag/CTagging/python/training_settings.py' % os.environ['CMSSW_BASE'], 'w') as output:
   output.write('import FWCore.ParameterSet.Config as cms\n')
   output.write('''
## IMPORTANT!
## This file was automatically generated by RecoBTag/CTagging/test/dump_training_vars_cfg.py
## with input xml files:
##    - C vs L: %s sha1 checksum: %s
##    - C vs B: %s sha1 checksum: %s 

''' % (args.CvsLXML, sha1_CvsLXML, args.CvsBXML, sha1_CvsBXML))
   output.write('c_vs_l_vars_vpset = %s\n' % CvsLXML_vpset.__repr__())
   output.write('\n\n')
   output.write('c_vs_b_vars_vpset = %s\n' % CvsBXML_vpset.__repr__())
   
   
