#!/usr/bin/env python3
"""Compares the calculator's answers (live.json) with the expected answers and with views_needed.py. usage: python3 analyze.py cases-expected.json live.json"""
import json
import re
import subprocess
from decimal import Decimal
import sys

exp = {c["id"]: c for c in json.load(open(sys.argv[1], encoding="utf-8"))}
live = json.load(open(sys.argv[2], encoding="utf-8"))
bad = 0
for r in live:
    e = exp[r["id"]]
    m = re.fullmatch(r"ESTIMATED EARNINGS \$?(-?[0-9][0-9,.]*) PER 1 MILLION VIEWS \$?(-?[0-9][0-9,.]*) VIEWS NEEDED FOR YOUR GOAL (.*)", r["answer"])
    got = [x.replace(",", "") for x in m.groups()] if m else []
    py = subprocess.run(["python3", "views_needed.py", "views", e["goal"], e["rpm"]], capture_output=True, text=True)
    if e["expect"] == "refuse":
        verdict = "tool says: " + r["answer"][:160] + " | script exit=" + str(py.returncode)
        print(f"{r['id']}: expected a refusal | {verdict}")
        continue
    want = [Decimal(e["earnings"]), Decimal(e["per_million"]), Decimal(e["views_needed"])]
    have = [Decimal(g) for g in got]
    ok_tool = have == want
    ok_py = py.stdout.strip() == f"Views needed: {e['views_needed']:,}"
    bad += (not ok_tool) + (not ok_py)
    print(f"{r['id']}: expected {[str(w) for w in want]} | tool {[str(h) for h in have]} {'OK' if ok_tool else 'DIFF'} | script {py.stdout.strip()!r} {'OK' if ok_py else 'DIFF'}")
print("DIFFS:", bad)
