import asyncio
import json
import unittest

from publisher import Message, Publisher


class RecordingTransport:
    def __init__(self) -> None:
        self.sent: list[int] = []

    def sendto(self, data: bytes, target: tuple[str, int]) -> None:
        self.sent.append(json.loads(data)["sequence"])


class ControlledEncoder:
    def __init__(self) -> None:
        self.first_started = asyncio.Event()
        self.release_first = asyncio.Event()

    async def __call__(self, message: Message) -> bytes:
        if message.sequence == 1:
            self.first_started.set()
            await self.release_first.wait()
        return json.dumps(
            {"sequence": message.sequence, "payload": message.payload}
        ).encode()


async def replay(serialized: bool) -> list[int]:
    transport = RecordingTransport()
    encoder = ControlledEncoder()
    publisher = Publisher(transport, encoder)
    publish = publisher.publish_serialized if serialized else publisher.publish
    second_started = asyncio.Event()

    async def second_call() -> None:
        second_started.set()
        await publish("second")

    first = asyncio.create_task(publish("first"))
    second = None
    try:
        await asyncio.wait_for(encoder.first_started.wait(), timeout=2)
        second = asyncio.create_task(second_call())
        await asyncio.wait_for(second_started.wait(), timeout=2)
        if not serialized:
            await asyncio.wait_for(asyncio.shield(second), timeout=2)
        encoder.release_first.set()
        await asyncio.wait_for(asyncio.gather(first, second), timeout=2)
        return transport.sent
    finally:
        for task in (first, second):
            if task is not None and not task.done():
                task.cancel()
        await asyncio.gather(
            *(task for task in (first, second) if task is not None),
            return_exceptions=True,
        )


class PublisherTests(unittest.IsolatedAsyncioTestCase):
    async def test_sequential_publishes_are_in_order(self) -> None:
        transport = RecordingTransport()

        async def encode(message: Message) -> bytes:
            return json.dumps({"sequence": message.sequence}).encode()

        publisher = Publisher(transport, encode)
        await publisher.publish("first")
        await publisher.publish("second")
        self.assertEqual(transport.sent, [1, 2])

    async def test_counterexample_reorders_the_unsafe_publisher(self) -> None:
        self.assertEqual(await replay(serialized=False), [2, 1])

    async def test_serialized_publisher_passes_the_same_scenario(self) -> None:
        self.assertEqual(await replay(serialized=True), [1, 2])


if __name__ == "__main__":
    unittest.main()
