#!/usr/bin/env python3
"""Fill the report template from numbers.json.

Every figure in the report is written as {{dotted.path}} and resolved from
numbers.json, so no number can be typed by hand. Integers are printed with
thousands separators. An unresolved placeholder is a hard error.
"""
import json, re, sys

NUM = json.load(open(sys.argv[1]))
TPL = open(sys.argv[2]).read()
OUT = sys.argv[3]


def lookup(path):
    cur = NUM
    for part in path.split("."):
        if isinstance(cur, list):
            cur = cur[int(part)]
        else:
            if part not in cur:
                raise KeyError(path)
            cur = cur[part]
    return cur


def fmt(v):
    if isinstance(v, bool):
        return str(v)
    if isinstance(v, int):
        return f"{v:,}"
    if isinstance(v, float):
        return f"{v:.1f}"
    return str(v)


missing = []


def sub(m):
    path = m.group(1).strip()
    try:
        return fmt(lookup(path))
    except (KeyError, IndexError, ValueError):
        missing.append(path)
        return "<<MISSING:%s>>" % path


out = re.sub(r"\{\{([^}]+)\}\}", sub, TPL)
if missing:
    sys.exit("unresolved placeholders: " + ", ".join(sorted(set(missing))))
open(OUT, "w").write(out)
print("wrote", OUT, len(out.split()), "words")
