"""Deterministic two-player rollback, using integer ticks and bounded history."""
from dataclasses import dataclass
import hashlib
import struct

LIMIT = 90
WIDTH = 4096


@dataclass(frozen=True, slots=True)
class Ship:
    x: int
    velocity: int = 0
    health: int = 4
    cooldown: int = 0


@dataclass(frozen=True, slots=True)
class Input:
    thrust: int = 0
    fire: bool = False

    def __post_init__(self):
        if self.thrust not in (-1, 0, 1):
            raise ValueError("thrust must be -1, 0 or 1")


def advance(state, inputs):
    moved = []
    firing = []
    for ship, command in zip(state, inputs, strict=True):
        speed = max(-80, min(80, ship.velocity + 9 * command.thrust))
        ready = ship.cooldown == 0 and ship.health > 0 and command.fire
        moved.append(Ship((ship.x + speed) % WIDTH, speed, ship.health,
                          12 if ready else max(0, ship.cooldown - 1)))
        firing.append(ready)
    separation = abs(moved[0].x - moved[1].x)
    close = min(separation, WIDTH - separation) < 500
    return tuple(Ship(ship.x, ship.velocity, max(0, ship.health - (close and firing[1 - slot])),
                      ship.cooldown) for slot, ship in enumerate(moved))


class Replay:
    """Recorded input can correct prediction within the last 90 ticks."""

    def __init__(self):
        self.tick = 0
        self.states = {0: (Ship(1500), Ship(2600))}
        self.confirmed = ({}, {})
        self.used = {}

    def step(self):
        tick = self.tick
        previous = self.used.get(tick - 1, (Input(), Input()))
        commands = tuple(self.confirmed[slot].get(tick, Input(prior.thrust))
                         for slot, prior in enumerate(previous))
        self.used[tick] = commands
        self.states[tick + 1] = advance(self.states[tick], commands)
        self.tick += 1
        oldest = self.tick - LIMIT
        self.states.pop(oldest - 1, None)
        self.used.pop(oldest - 2, None)
        for inputs in self.confirmed:
            inputs.pop(oldest - 1, None)

    def submit(self, slot, tick, command):
        if slot not in (0, 1) or not max(0, self.tick - LIMIT) <= tick <= self.tick + LIMIT:
            raise ValueError("input outside supported player or tick window")
        if not isinstance(command, Input):
            raise TypeError("expected Input")
        known = self.confirmed[slot].get(tick)
        if known is not None and known != command:
            raise ValueError("conflicting confirmed input")
        self.confirmed[slot][tick] = command
        if tick >= self.tick or self.used[tick][slot] == command:
            return 0
        head = self.tick
        self.tick = tick
        while self.tick < head:
            self.step()
        return head - tick

    def checksum(self):
        return hashlib.blake2s(b"".join(struct.pack(">4i", ship.x, ship.velocity,
                               ship.health, ship.cooldown) for ship in self.states[self.tick]),
                               digest_size=8).hexdigest()


if __name__ == "__main__":
    on_time, delayed = Replay(), Replay()
    on_time.submit(1, 8, Input(-1, True))
    for _ in range(32):
        on_time.step()
        delayed.step()
    replayed = delayed.submit(1, 8, Input(-1, True))
    assert delayed.checksum() == on_time.checksum()
    print(f"Replayed {replayed} ticks. Both simulations agree: {delayed.checksum()}")

