"""Enumerate the same two unknown routes as progressively more evidence is supplied."""
import argparse
from datetime import datetime, timezone
from hashlib import sha256
from itertools import product
import json
from pathlib import Path
import platform

from replay import ROUTES, bounds, cost_micro_usd

HERE = Path(__file__).resolve().parent


def compare(ledger):
    reference = bounds(ledger)
    unknown = [row for row in ledger["calls"] if row["route"] is None]
    if len(unknown) != 2 or "C" not in {row["id"] for row in unknown}:
        raise ValueError("this comparison requires two unknown routes, including call C")

    results = {"known_labels_only": [], "with_route_counts": [], "with_counts_and_C_on_economy": []}
    for destinations in product(ROUTES, repeat=len(unknown)):
        proposed = {row["id"]: route for row, route in zip(unknown, destinations)}
        counts = dict.fromkeys(ROUTES, 0)
        total = 0
        for row in ledger["calls"]:
            route = row["route"] or proposed[row["id"]]
            counts[route] += 1
            total += cost_micro_usd(row, ledger["rates_usd_per_million"][route])
        outcome = {"hypothetical_routes": proposed, "total_micro_usd": total}
        results["known_labels_only"].append(outcome)
        if counts == ledger["observed_calls_by_route"]:
            results["with_route_counts"].append(outcome)
            if proposed["C"] == "economy":
                results["with_counts_and_C_on_economy"].append(outcome)

    constrained = [row["total_micro_usd"] for row in results["with_route_counts"]]
    if (min(constrained), max(constrained)) != (
        reference["minimum"]["total_micro_usd"], reference["maximum"]["total_micro_usd"]
    ):
        raise ValueError("enumeration disagrees with the two-route bounds")
    return results


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--check", action="store_true", help="compare results and inputs with the archived run")
    args = parser.parse_args()
    inputs = ["fixture.json", "replay.py", "compare_controls.py"]
    fingerprints = {name: sha256((HERE/name).read_bytes()).hexdigest() for name in inputs}
    results = compare(json.loads((HERE/"fixture.json").read_text()))
    if args.check:
        archived = json.loads((HERE/"control-comparison.json").read_text())
        if archived["results"] != results or archived["sha256"] != fingerprints:
            raise SystemExit("Evidence comparison differs from the archived run")
        print("All three evidence conditions reproduced with matching input and code hashes.")
    else:
        print(json.dumps({
            "author": "Anant Mishra",
            "scope": "Fictional four-call fixture. The restored economy label for C is a hypothetical observation.",
            "executed_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"),
            "python": platform.python_version(),
            "command": "python3 -B compare_controls.py",
            "sha256": fingerprints,
            "results": results
        }, indent=2))
