"""Chain-link CBS monthly CPI (series 120010) into annual averages with 2024 = 100.

Each base period 'Average YYYY' is defined so that year YYYY averages 100 on it; the same
year's average on the previous base is the link factor between the two bases.
"""
import json, sys
from collections import defaultdict
rows = json.load(open(sys.argv[1]))["month"][0]["date"]
by = defaultdict(lambda: defaultdict(list))  # base -> year -> values
for r in rows:
    by[r["currBase"]["baseDesc"]][r["year"]].append(r["currBase"]["value"])
avg = {b: {y: sum(v) / len(v) for y, v in ys.items() if len(v) == 12} for b, ys in by.items()}
bases = sorted(avg, key=lambda b: int(b.split()[-1]))
# factor converting a value on base b into base 'Average 2014' units
factor = {bases[0]: 1.0}
for prev, cur in zip(bases, bases[1:]):
    base_year = int(cur.split()[-1])
    factor[cur] = factor[prev] * avg[prev][base_year] / 100
annual = {}
for b in bases:
    for y, v in avg[b].items():
        annual[y] = v * factor[b]
ref = annual[2024]
out = {y: round(100 * annual[y] / ref, 2) for y in sorted(annual)}
json.dump(out, open(sys.argv[2], "w"), indent=1)
print(out)
