"""Replay the invented harbour ledger. Run with Python 3, no packages required."""
import json
from fractions import Fraction
from itertools import product

# The events are incremental. The board sees events only through its chosen cut.
EVENTS = [
    dict(day=0, purchase=12, invoice=7200),
    dict(day=0, due=4, signed=4),
    dict(day=1, due=1, signed=0, exception="Monday tide missed. The mounting shoe for the east light was missing."),
    dict(day=2, due=1, signed=1),
]
DAYS = ["Friday", "Monday", "Tuesday"]


def snapshot(day):
    visible = [row for row in EVENTS if row["day"] <= day]
    def total(field):
        return sum(row.get(field, 0) for row in visible)
    quantity, invoice, due, signed = (total(key) for key in ("purchase", "invoice", "due", "signed"))
    return dict(day=DAYS[day], invoice=invoice, bought=quantity, due=due, signed=signed,
                stock=quantity-signed, short=due-signed,
                quotient=int(Fraction(invoice, signed)),
                issued=int(Fraction(invoice*signed, quantity)),
                exceptions=[row["exception"] for row in visible if "exception" in row])


def minute(cut, plan, stock, log):
    entries = []
    if plan:
        entries.append(f'{cut["due"]} due, {cut["signed"]} signed. ' +
                       ('Programme met at this cut.' if not cut["short"] else f'{cut["short"]} installation outstanding against plan.'))
    if stock:
        entries.append(f'{cut["stock"]} of the 12 remain in store. The invoice covers these too.')
    if log:
        entries += cut["exceptions"] or ["No missed window entered by this cut."]
    if not entries:
        entries.append("Only the invoice and sign-offs survive in this minute.")
    return " ".join(entries)


def replay():
    cuts = [snapshot(day) for day in range(len(DAYS))]
    reports = {}
    for i, cut in enumerate(cuts):
        for flags in product((0, 1), repeat=3):
            key = str(i) + "-" + "".join(map(str, flags))
            reports[key] = minute(cut, *flags)
    assert [(c["due"], c["signed"], c["quotient"]) for c in cuts] == [(4,4,1800),(5,4,1800),(6,5,1440)]
    assert [c["issued"] for c in cuts] == [2400, 2400, 3000]
    assert all(c["issued"] + c["stock"] * 600 == c["invoice"] for c in cuts)
    assert not cuts[0]["exceptions"] and cuts[1]["exceptions"] == cuts[2]["exceptions"]
    assert all(("mounting shoe" in value) == (key[0] != "0" and key[-1] == "1") for key, value in reports.items())
    assert len(reports) == 24
    return dict(cuts=cuts, reports=reports)


if __name__ == "__main__":
    print(json.dumps(replay(), ensure_ascii=False, indent=2))
