"""Deterministic structured-event replay. Run with Python 3.8+; no dependencies."""
import argparse
from collections import Counter
from dataclasses import dataclass
import json
import random


@dataclass(frozen=True)
class Event:
    topic: str
    kind: str
    day: str
    audience: str
    source_order: int


@dataclass(frozen=True)
class Decision:
    action: str
    day: str = ""


FAMILIES = (
    "confirmed", "rescheduled", "cancelled", "private_update", "tentative",
    "no_evidence", "other_room", "late_copy",
)
DAYS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")


def fixture(family, rng):
    first, second, third = rng.sample(DAYS, 3)
    public = lambda day, order: Event("lantern", "confirmed", day, "public", order)
    original = public(first, 1)
    histories = {
        "confirmed": [original, public(first, 2)],
        "rescheduled": [original, public(second, 2)],
        "cancelled": [original, Event("lantern", "cancelled", "", "public", 2)],
        "private_update": [original, Event("lantern", "confirmed", second, "agent-private", 2)],
        "tentative": [Event("lantern", "tentative", first, "public", 1)],
        "no_evidence": [],
        "other_room": [original, Event("lantern", "confirmed", third, "another-room", 2)],
        "late_copy": [original, public(second, 2), original],
    }
    expected = {
        "confirmed": Decision("announce", first),
        "rescheduled": Decision("announce", second),
        "cancelled": Decision("stay_closed"),
        "private_update": Decision("ask_privately"),
        "tentative": Decision("verify"),
        "no_evidence": Decision("verify"),
        "other_room": Decision("announce", first),
        "late_copy": Decision("announce", second),
    }
    events = histories[family][:]
    for _ in range(rng.randrange(2, 10)):
        noise = Event("ferry", "confirmed", rng.choice(DAYS), "public", 1)
        events.insert(rng.randrange(len(events) + 1), noise)
    return events, expected[family]


def render_naively(matches):
    if not matches:
        return Decision("verify")
    if matches[-1].kind == "cancelled":
        return Decision("stay_closed")
    return Decision("announce", matches[-1].day)


def recent(events):
    return render_naively([e for e in events[-2:] if e.topic == "lantern"])


def archive(events):
    return render_naively([e for e in events if e.topic == "lantern"])


def scoped_state(events):
    # The harness contract permits the clerk to see private updates, but forbids
    # it from using other-room events or disclosing an agent-private day publicly.
    visible = [e for e in events if e.topic == "lantern" and e.audience != "another-room"]
    if not visible:
        return Decision("verify")
    current = max(visible, key=lambda e: e.source_order)
    if current.audience == "agent-private":
        return Decision("ask_privately")
    if current.kind == "tentative":
        return Decision("verify")
    return render_naively([current])


POLICIES = {"recent_two": recent, "archive_latest": archive, "scoped_state": scoped_state}


def evaluate(seed, per_family):
    rng = random.Random(seed)
    totals = {policy: Counter() for policy in POLICIES}
    by_family = {}
    for family in FAMILIES:
        counts = Counter()
        for _ in range(per_family):
            events, expected = fixture(family, rng)
            for name, decide in POLICIES.items():
                result = decide(events)
                match = result == expected
                counts[name] += int(match)
                totals[name]["correct"] += int(match)
                totals[name]["cases"] += 1
                if result.action == "announce":
                    if any(e.day == result.day and e.topic == "lantern" and
                           e.audience in ("agent-private", "another-room") for e in events):
                        totals[name]["restricted_day_announced"] += 1
        by_family[family] = dict(counts)
    return {"seed": seed, "per_family": per_family, "per_policy": totals,
            "correct_by_family": by_family}


if __name__ == "__main__":
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--seed", type=int, default=24)
    p.add_argument("--per-family", type=int, default=25)
    args = p.parse_args()
    if args.per_family < 1:
        p.error("--per-family must be positive")
    print(json.dumps(evaluate(args.seed, args.per_family), indent=2))
