#! /usr/bin/python3

"""\
%prog <ipolfile>

List the interpolations stored in <ipolfile>. Useful for writing a default weights file.
"""

import optparse, os, sys
op = optparse.OptionParser(usage=__doc__)
op.add_option("-w", dest="WFILE", default=False, action="store_true", help="Output suitable for weightfile")
op.add_option("-p", dest="PARAMS", default=False, action="store_true", help="Print valid parameter range")
op.add_option("-v", "--debug", dest="DEBUG", action="store_true", default=False, help="Turn on some debug messages")
op.add_option("-q", "--quiet", dest="QUIET", action="store_true", default=False, help="Turn off messages")
opts, args = op.parse_args()

## Get mandatory arguments
if len(args) < 1:
    print("Argument missing... exiting\n\n")
    op.print_usage()
    sys.exit(1)
IFILE = args[0]


## Load Professor and show the standard banner
import professor2 as prof

## Read persisted interpolations to re-create the ipol Histos
IHISTOS, META = prof.read_ipoldata(IFILE)
maxlen = max(len(h) for h in list(IHISTOS.keys()))
hfmt = "{0:%ds}" % maxlen





## Democratic weights file to std out
if opts.WFILE:
    curr = ""
    for path, h in sorted(IHISTOS.items()):
        new = path.split("/")[1]
        if curr != new:
            curr = new
        s = hfmt.format(path)
        s += "   1.0   # {n:d} bins from {xmin:g} to {xmax:g}".format(n=len(h), xmin=h.bins[0].xmin, xmax=h.bins[-1].xmax)
        print(s)

## Simply print the parameterisation ranges
elif opts.PARAMS:
    s=""
    PNAMES=META["ParamNames"].split()
    lmax = max([len(x) for x in PNAMES])
    for num, p in enumerate(PNAMES):
        s+="%s\t%s\t%s"%(p.ljust(lmax), META["MinParamVals"].split()[num], META["MaxParamVals"].split()[num])
        if num<len(PNAMES)-1:
            s+="\n"
    print(s)

else:
    ## Print!
    if opts.DEBUG:
        print("Metadata:")
        for k, v in sorted(META.items()):
            print(" ", k, "=", v)
        print("\n")
    else:
        print("\nObjects:")
        for path, h in sorted(IHISTOS.items()):
            print(" ", hfmt.format(path)) #+ "  " + ...

        print("\nRanges of parameters:")
        s=""
        PNAMES=META["ParamNames"].split()
        lmax = max([len(x) for x in PNAMES])
        for num, p in enumerate(PNAMES):
            s+="%s\t%s\t%s"%(p.ljust(lmax), META["MinParamVals"].split()[num], META["MaxParamVals"].split()[num])
            if num<len(PNAMES)-1:
                s+="\n"
        print(s)
