#!/usr/bin/env python3
"""
process data generated by PageBuilder
"""

import json

INFN  = "document.json"
OUTFN = "_DATA.json"

TOC_LINE = "<li>{}</li>"
TOC = """
<ol>
{}
</ol>
"""


print ("PROCESSING ===========================================================")

print ("reading", INFN)
with open(INFN, "r") as f: document_json = f.read()
print ("parsing", INFN)
document_data = json.loads(document_json)
print ("analysing {} ({} records)".format(INFN, len(document_data)))

sum_magicnums = 0
magicwords = []
headings = []
for r in document_data:
    if "magicnum" in r:
        sum_magicnums += int(r["magicnum"])
    if "magicword" in r:
        magicwords.append(r["magicword"])
    if "heading" in r:
        headings.append(r["heading"])

# magic
magicwords = ", ".join(magicwords)
print("magic words:", magicwords)
print("sum magic numbers:", sum_magicnums)

# TOC
print("headings:", headings)
toc = "\n".join(TOC_LINE.format(h) for h in headings)
toc = TOC.format(toc)
print("toc:")
print(toc)


with open(OUTFN, "w") as f: f.write(json.dumps({
    "sum_magicnums":    sum_magicnums,
    "aggr_magicwords":  magicwords,
    "toc":              toc,
}))


print ("END PROCESSING =======================================================")
