"""Reproduce the frozen EB5Status calls with Python 3, using no network or third-party modules.

python3 replay.py frozen-snapshot.json [backtest.json]
The optional argument verifies the two-edition direction calls and aggregate scores from the included vintage rows.
"""
import hashlib
import json
import sys
from datetime import date


def state(v):
    if v in ("C", "U"):
        return v
    if not v or date.fromisoformat(v).isoformat() != v:
        raise ValueError("Unrecognized cutoff")
    return "dated"


def forecast(c, target):
    return "hold" if c["baseline"] == c["previous"] and c["category"] != "infrastructure" and not target.endswith("-10") else "abstain"


def check_snapshot(document):
    snapshot = document["snapshot"]
    data = json.dumps(snapshot, ensure_ascii=False, separators=(",", ":")).encode()
    if hashlib.sha256(data).hexdigest() != document["sha256"]:
        raise ValueError("Snapshot checksum mismatch")
    cells = snapshot["cells"]
    if len(cells) != 40 or len({(c["chart"], c["category"], c["chargeability"]) for c in cells}) != 40:
        raise ValueError("Incomplete cell identity")
    for c in cells:
        state(c["baseline"])
        if c["call"] != forecast(c, snapshot["target"]):
            raise ValueError("Call differs from frozen inputs")
    return {"target":snapshot["target"], "verified":len(cells), "calls":sum(c["call"]=="hold" for c in cells)}


def check_backtest(report):
    for name in ("model", "no-change"):
        rows = report["rows"] if name == "no-change" else [c for c in report["rows"] if forecast(c,c["target"]) == "hold"]
        dates = [r for r in rows if state(r["actual"]) == state(r["baseline"]) == "dated"]
        result = dict(calls=len(rows), stateHits=sum(state(r["actual"])==state(r["baseline"]) for r in rows),
                      directionHits=sum(r["actual"]==r["baseline"] for r in rows), datedPairs=len(dates),
                      absoluteDays=sum(abs((date.fromisoformat(r["actual"])-date.fromisoformat(r["baseline"])).days) for r in dates))
        if any(report["totals"][name][key] != value for key,value in result.items()):
            raise ValueError("Backtest differs: "+name)
        print(name,result)


if __name__ == "__main__":
    with open(sys.argv[1], encoding="utf8") as source:
        print(check_snapshot(json.load(source)))
    if len(sys.argv)>2:
        with open(sys.argv[2], encoding="utf8") as source:
            check_backtest(json.load(source))
