"""Generate a fictional baseball schedule-change dataset using Python 3.9+."""
import argparse
import hashlib
import json
from datetime import datetime, timedelta, timezone


# Minutes are relative to the original scheduled first pitch. Each change is
# observed at the first offset; a third value sets a new scheduled start.
PLAY = [(0, "first_pitch"), (160, "final")]
CASES = {
    "played-as-listed": PLAY,
    "start-moved-earlier": [(-180, "retime", -60), (-60, "first_pitch"), (100, "final")],
    "start-moved-later": [(-120, "retime", 90), (90, "first_pitch"), (245, "final")],
    "start-moved-past-midnight-utc": [(-60, "retime", 720), (720, "first_pitch"), (880, "final")],
    "delayed-without-estimate": [(-10, "delay"), (44, "first_pitch"), (210, "final")],
    "revised-delay-estimate": [(-15, "delay"), (-5, "retime", 30), (20, "retime", 75), (76, "first_pitch"), (230, "final")],
    "postponed-next-day": [(-40, "postpone"), (30, "reschedule", 1440), (1440, "first_pitch"), (1600, "final")],
    "postponed-date-unknown": [(-90, "postpone")],
    "postponed-twice": [(-20, "postpone"), (5, "reschedule", 1440), (1400, "postpone"), (1460, "reschedule", 2880), (2880, "first_pitch"), (3060, "final")],
    "cancelled-before-start": [(-25, "cancel")],
    "cancelled-after-postponement": [(-120, "postpone"), (1440, "cancel")],
    "suspended-and-resumed": [(0, "first_pitch"), (55, "suspend"), (95, "resume"), (205, "final")],
    "two-interruptions": [(0, "first_pitch"), (35, "suspend"), (63, "resume"), (100, "suspend"), (141, "resume"), (223, "final")],
    "resumed-next-day": [(0, "first_pitch"), (70, "suspend"), (1440, "resume"), (1525, "final")],
    "abandoned-during-play": [(0, "first_pitch"), (48, "abandon")],
    "abandoned-after-suspension": [(0, "first_pitch"), (85, "suspend"), (190, "abandon")],
    "moved-to-neutral-ground": [(-90, "move_to_neutral")] + PLAY,
    "neutral-from-scheduling": PLAY,
    "doubleheader-game-one": PLAY,
    "doubleheader-game-two": PLAY,
}
TRANSITIONS = {
    "delay": ({"scheduled"}, "delayed"),
    "retime": ({"scheduled", "delayed"}, None),
    "postpone": ({"scheduled", "delayed"}, "postponed"),
    "reschedule": ({"postponed"}, "scheduled"),
    "cancel": ({"scheduled", "delayed", "postponed"}, "cancelled"),
    "first_pitch": ({"scheduled", "delayed"}, "playing"),
    "suspend": ({"playing"}, "suspended"),
    "resume": ({"suspended"}, "playing"),
    "abandon": ({"playing", "suspended"}, "abandoned"),
    "final": ({"playing"}, "completed"),
    "move_to_neutral": ({"scheduled"}, None),
}
CLUBS = ("Cinder Pier Lanterns", "Lockhouse Kites", "Quarry Bend Rooks",
         "Glassworks Terns", "Tin Wharf Spindles", "Kiln Gate Tides")
VENUES = ("Lantern Plot", "Kite Plot", "Rook Plot", "Tern Plot", "Spindle Plot", "Tide Plot")
NEUTRAL = "Switchyard Field"


def stamp(clock):
    return clock.isoformat(timespec="minutes").replace("+00:00", "Z")


def make_fixture(seed, slot):
    case = list(CASES)[slot % len(CASES)]
    game_number = {"doubleheader-game-one": 1, "doubleheader-game-two": 2}.get(case)
    group_slot = slot - 1 if game_number == 2 else slot
    # A fixed hash selects invented participants without a network or database.
    pick = hashlib.sha256(f"{seed}:{group_slot}".encode()).digest()
    home = pick[0] % len(CLUBS)
    away = (home + 1 + pick[1] % (len(CLUBS) - 1)) % len(CLUBS)
    # Three days between unrelated fixtures keep these example clubs available.
    start = datetime(2040, 6, 1, 15, tzinfo=timezone.utc) + timedelta(days=group_slot * 3)
    if game_number == 2:
        start += timedelta(hours=5)
    def at(minutes):
        return stamp(start + timedelta(minutes=minutes))

    state = "scheduled"
    neutral = case == "neutral-from-scheduling"
    venue = NEUTRAL if neutral else VENUES[home]
    scheduled = at(0)
    history = []

    def snapshot(offset, change):
        history.append(dict(sequence=len(history) + 1, observed_at=at(offset),
                            change=change, state=state, scheduled_start=scheduled,
                            venue=venue, neutral=neutral))

    snapshot(-1440, "listed")
    for offset, change, *new_start in CASES[case]:
        allowed, next_state = TRANSITIONS[change]
        if state not in allowed:
            raise ValueError(f"{case}: {change} from {state}")
        state = next_state or state
        if new_start:
            scheduled = at(new_start[0])
        elif change in {"postpone", "cancel", "delay"}:
            scheduled = None
        elif change == "move_to_neutral":
            neutral, venue = True, NEUTRAL
        snapshot(offset, change)

    return dict(fixture_id=f"FIC-{slot + 1:03}", case=case, home=CLUBS[home], away=CLUBS[away],
                doubleheader_id=f"DH-{group_slot + 1:03}" if game_number else None,
                game_number=game_number, history=history)


def generate(seed=41):
    fixtures = [make_fixture(seed, slot) for slot in range(50)]
    return dict(schema="fictional-baseball-lifecycle/v1", seed=seed, fictional=True,
                provenance="Invented teams, venues and event histories. No source game data.",
                time_basis="UTC", fixture_count=len(fixtures), case_count=len(CASES),
                fixtures=fixtures)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--seed", type=int, default=41,
                        help="select fictional opponents while preserving all 20 scenarios")
    args = parser.parse_args()
    print(json.dumps(generate(args.seed), indent=2))
