# Compares the expected CPM written first (expected.py), the live Koldflux CPM calculator and cpm.py for every case.
import json, re, subprocess, sys
exp = json.load(open(sys.argv[1], encoding="utf-8"))
live = {r["id"]: r for r in json.load(open(sys.argv[2], encoding="utf-8"))}
ok_tool = ok_script = 0
for c in exp:
    t = live[c["id"]]["answer"]
    m = re.match(r"^(-?[\d,]+(?:\.\d+)?) USD per 1,000", t)
    tool = m.group(1).replace(",", "") if m else "no number"
    p = subprocess.run([sys.executable, "cpm.py", "cpm", c["spend"] or "x", c["impressions"] or "x"], capture_output=True, text=True)
    mm = re.match(r"CPM = (-?[\d.]+) per 1,000", p.stdout)
    script = (mm.group(1).rstrip("0").rstrip(".") if mm and "." in mm.group(1) else (mm.group(1) if mm else "no number"))
    want = c["expected"]
    tool_ok = (tool == want) or (want == "no number" and tool == "no number")
    script_ok = (script == want) or (want == "no number" and script == "no number")
    ok_tool += tool_ok; ok_script += script_ok
    print("%-24s expected=%-12s tool=%-12s script=%-12s %s %s | tool text: %s" % (c["id"], want, tool, script, "TOOL-OK" if tool_ok else "TOOL-DIFF", "SCRIPT-OK" if script_ok else "SCRIPT-DIFF", t))
print("tool agrees on %d of %d, script on %d of %d" % (ok_tool, len(exp), ok_script, len(exp)))
