"""Replay one fictional Glasshouse handover desk. Python 3, standard library."""
from collections import Counter
from itertools import product
import json
from pathlib import Path

# Minutes from 08:00. The release slip records when it was signed and when filed.
BAYS = ("Intake", "Return")
STATES = ("unsigned", "prompt", "late", "sent")
CALLS = (60, 75, 90, 110, 120)
ARRIVALS = (0, 20)
SIGNATURES = (40, 65)
LATE_FILE = (110, 115)
DISPATCHES = (95, 85)


def fmt(minutes):
    return f"{8 + minutes // 60:02d}:{minutes % 60:02d}"


def events(bay, profile):
    i = BAYS.index(bay)
    logs = [(bay, "arrival", ARRIVALS[i], ARRIVALS[i])]
    if profile != "unsigned":
        filed = LATE_FILE[i] if profile == "late" else SIGNATURES[i]
        logs.append((bay, "release", SIGNATURES[i], filed))
    if profile == "sent":
        logs.append((bay, "dispatch", DISPATCHES[i], DISPATCHES[i]))
    return logs


def choose(eligible, times):
    return min(eligible, key=times.get, default=None)


def instructions(records, when, shortcut=None):
    # Every row is (bay, kind, occurred, logged). An overdue slip might never arrive.
    known = {bay: {} for bay in BAYS}
    for bay, kind, occurred, logged in records:
        if (occurred if shortcut == "hindsight" else logged) <= when:
            known[bay][kind] = occurred
    waiting = [bay for bay, row in known.items() if "arrival" in row and "dispatch" not in row]
    calls = [bay for bay in waiting if "release" not in known[bay]]
    basis = "arrival" if shortcut == "oldest" else "release"
    eligible = {bay: known[bay][basis] for bay in waiting if basis in known[bay]}
    return {"crew": choose(eligible, eligible), "chase": calls}


def oracle(profiles, when):
    # Check the date and queue rule directly from the four named histories, without a ledger.
    queue, calls = [], []
    for i, state in enumerate(profiles):
        if state == "sent" and when >= DISPATCHES[i]:
            continue
        threshold = LATE_FILE[i] if state == "late" else SIGNATURES[i]
        if state != "unsigned" and when >= threshold:
            queue.append((SIGNATURES[i], BAYS[i]))
        else:
            calls.append(BAYS[i])
    return {"crew": min(queue)[1] if queue else None, "chase": calls}


def run():
    patterns, results = {}, []
    tally = Counter()
    for profiles in product(STATES, repeat=2):
        key = "/".join(profiles)
        event_list = [row for bay, state in zip(BAYS, profiles) for row in events(bay, state)]
        patterns[key] = event_list
        for now in CALLS:
            # Construct both displays as of the call. Cards are grouped by bay and filed time.
            visible = [e for e in event_list if e[3] <= now]
            cards = {b: sorted([e for e in visible if e[0] == b], key=lambda e: e[3]) for b in BAYS}
            # The trace projects onto event time and records the filing time on every mark.
            trace = sorted(visible, key=lambda e: (e[2], e[0], e[1]))
            card_rows = [e for bay in BAYS for e in cards[bay]]
            expected = oracle(profiles, now)
            assert sorted(card_rows) == sorted(trace)
            assert instructions(card_rows, now) == instructions(trace, now) == expected
            oldest = instructions(event_list, now, "oldest")["crew"]
            hindsight = instructions(event_list, now, "hindsight")
            tally["decisions"] += 1
            tally["oldest_wrong_crew"] += oldest != expected["crew"]
            tally["hindsight_wrong_crew"] += hindsight["crew"] != expected["crew"]
            tally["hindsight_wrong_instruction"] += hindsight != expected
            tally["oldest_assigns_unsigned"] += oldest in expected["chase"]
            results.append(dict(case=key, at=now, answer=expected, oldest=oldest, hindsight=hindsight))
    check = {r["at"]: r["answer"] for r in results if r["case"] == "late/prompt"}
    assert check[90] == {"crew": "Return", "chase": ["Intake"]}
    assert check[110] == {"crew": "Intake", "chase": []}
    assert all((e[2] <= e[3]) for records in patterns.values() for e in records)
    return {"bays": BAYS, "states": STATES, "calls": CALLS, "patterns": patterns,
            "results": results, "counts": dict(tally)}


if __name__ == "__main__":
    output = run()
    Path(__file__).with_name("results.json").write_text(json.dumps(output, separators=(",", ":")) + "\n")
    print(json.dumps(output["counts"], indent=2))
