"""Replay the fictional two-commission school brief. Requires only Python 3."""
import itertools
import json
from pathlib import Path


def trial(commission, layout, handover, walk_cost, sequence):
    if layout == "spare":
        advice = "hatch"
    elif commission == "hall" or (handover == "walk" and layout == "crossing"):
        advice = "banks"
    else:
        advice = "hatch"
    action = advice if sequence == "advice" else sequence
    missed = int(action == "hatch" and layout == "crossing")
    rework = 7 * missed
    first = 8 if commission == "live" else 6
    transfer = walk_cost if handover == "walk" else 0
    second = (7 if action == "hatch" else 11) + rework
    return dict(commission=commission, layout=layout, handover=handover, walkCost=walk_cost,
                sequence=sequence, recommendation=advice, action=action, first=first,
                transfer=transfer, second=second, rework=rework, total=first+transfer+second,
                missed=missed, waits="Elm" if commission == "live" else "Larch")


def main():
    grid = itertools.product(("hall", "live"), ("straight", "crossing", "spare"),
                             ("report", "walk"), range(4), ("advice", "hatch", "banks"))
    cases = [trial(*parameters) for parameters in grid]
    standard = [r for r in cases if r["walkCost"] == 1 and r["sequence"] == "advice"]
    expected = {("hall", "straight"): (17, 18), ("hall", "crossing"): (17, 18),
                ("hall", "spare"): (13, 14), ("live", "straight"): (15, 16),
                ("live", "crossing"): (22, 20), ("live", "spare"): (15, 16)}
    assert len(cases) == 144 and len(standard) == 12
    for r in standard:
        assert r["total"] == expected[r["commission"], r["layout"]][r["handover"] == "walk"]
        assert r["missed"] == int((r["commission"], r["layout"], r["handover"]) ==
                                  ("live", "crossing", "report"))
    for r in cases:
        assert r["total"] == r["first"] + r["transfer"] + r["second"]
        assert r["rework"] == 7 * r["missed"]
    result = {"standard": standard, "cases": cases}
    Path(__file__).with_name("results.json").write_text(json.dumps(result, indent=2) + "\n")
    print("144 replays verified, including all 12 standard decisions.")


if __name__ == "__main__":
    main()
