#!/usr/bin/env python3
# Copyright (c) 2018 Arista Networks, Inc.  All rights reserved.
# Arista Networks, Inc. Confidential and Proprietary.

#pylint: disable-msg=W0106,W0621

import sys
import json
import optparse # pylint: disable=deprecated-module

parser = optparse.OptionParser( description="parse qtprof output" )

parser.add_option('-p', '--parseable',
                  dest='parsable', action='store_true',
                  help='count values are parsable (generated by qtcat --parsable)')
parser.add_option('-b', '--brief',
                  dest='brief', action='store_true',
                  help='print profiling information for function names only')

(options, args) = parser.parse_args()

if not args:
   inputFiles = [ sys.stdin ]
else:
   # pylint: disable-next=consider-using-with
   inputFiles = [ open( f ) for f in args ]

# opposite of int2hr (in qtcat)
def hr2int(hr):
   if 'x' not in hr:
      return int(hr)
   if hr.endswith('Kx'):
      return int(hr[:-2]) * 1000
   if hr.endswith('Mx'):
      return int(hr[:-2]) * 1000000
   if hr.endswith('Gx'):
      return int(hr[:-2]) * 1000000000
   if hr.endswith('Tx'):
      return int(hr[:-2]) * 1000000000000
   if hr.endswith('Px'):
      return int(hr[:-2]) * 1000000000000000
   if hr.endswith('x'):
      return int(hr[:-1])
   return ''

# must match definition in qtcat
def addJsonProfilingInfo(qtfile, filename, line, msg, count, avg, total):
   #pylint: disable-msg=E0602
   global JSON
   JSON += [ {
      "qt": qtfile,
      "file": filename,
      "line": line,
      "msg": msg,
      "count": count,
      "average": (avg[:-1].strip() if avg != '-' else 'None'),
      "total": (total[:-1].strip() if total != '-' else 'None')
   } ]

JSON = []

for inputFile in inputFiles:
   for line in inputFile:
      line = line.split()
      if len(line) < 7:
         continue
      try:
         msgCount = int(line[0].replace('*', ''))
         count = int(line[1]) if options.parsable else hr2int(line[1])
         avg = line[4]
         total = line[5]
         if options.brief and (avg == '-' or total == '-'):
            continue
         file_ln = line[6]
         file_ln = file_ln.split(':')
         filename = file_ln[0]
         ln = int(file_ln[1])
         msg = ' '.join(line[7:]).replace('"','')

         addJsonProfilingInfo(None, filename, ln, msg, count, avg, total)

      except ValueError as e:
         pass

[ f.close() for f in inputFiles ]

print( json.dumps( JSON, indent=2 ) )
