# Writes the expected CPM of every case BEFORE any tool sees it. Python Decimal, spend / impressions * 1000.
import json, sys
from decimal import Decimal, getcontext, ROUND_HALF_UP
getcontext().prec = 40
cases = json.load(open(sys.argv[1], encoding="utf-8"))
for c in cases:
    try:
        if Decimal(c["spend"]) < 0:
            raise ValueError("negative spend: refusal is the expected answer")
        v = Decimal(c["spend"]) / Decimal(c["impressions"]) * 1000
        c["expected"] = (format(v.quantize(Decimal("0.0001"), rounding=ROUND_HALF_UP), "f").rstrip("0").rstrip(".") if "." in format(v.quantize(Decimal("0.0001"), rounding=ROUND_HALF_UP), "f") else format(v.quantize(Decimal("0.0001"), rounding=ROUND_HALF_UP), "f"))
    except Exception:
        c["expected"] = "no number"
json.dump(cases, open(sys.argv[2], "w", encoding="utf-8"), indent=1)
for c in cases: print(c["id"], c["spend"], c["impressions"], "->", c["expected"])
