"""Read a fixed teaching snapshot and compare two named work-order histories."""
import argparse
from datetime import date
import hashlib
import json
from pathlib import Path

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("input", type=Path)
parser.add_argument("report", type=Path, help="new report filename")
args = parser.parse_args()
raw = args.input.read_bytes()
digest = hashlib.sha256(raw).hexdigest()
if digest != "dee6b1a5ba1900b4dc8944d5fe01eb0c858dae0392cf1d813f998b7bf950698c":
    parser.error("use the fixed upstream work_orders.json, with its original bytes")

def timeline(order, pointer):
    events = [
        {"date": event["date"], "action": event["action"], "pointer": f"{pointer}/history/{i}"}
        for i, event in enumerate(order["history"])
    ]
    days = [date.fromisoformat(event["date"]) for event in events]
    last_day = max(days)
    return {
        "id": order["work_order_id"],
        "status": order["status"],
        "statusPointer": f"{pointer}/status",
        "history": events,
        "latestRecordedDay": last_day.isoformat(),
        "eventsOnLatestDay": [e["pointer"] for e, day in zip(events, days) if day == last_day],
    }

orders = json.loads(raw)
by_id = {order["work_order_id"]: (i, order) for i, order in enumerate(orders)}
results = []
for identifier in ("WO-1002", "WO-1001"):
    position, order = by_id[identifier]
    results.append(timeline(order, f"/{position}"))
report = {"inputSha256": digest, "datePrecision": "day", "orders": results}
with args.report.open("x", encoding="utf-8") as output:
    json.dump(report, output, ensure_ascii=False, indent=2)
    output.write("\n")
for r in results:
    print(r["id"], r["status"], r["latestRecordedDay"], *r["eventsOnLatestDay"])
