"""本机回环实验。Python 3.11–3.13，在虚拟环境装入 amqtt==0.11.3。"""
import asyncio
from contextlib import asynccontextmanager
from importlib.metadata import version
from amqtt.broker import Broker


def string(value):
    raw = value.encode("utf-8")
    return len(raw).to_bytes(2, "big") + raw


@asynccontextmanager
async def local_broker(plugins=None):
    options = {"amqtt.plugins.authentication.AnonymousAuthPlugin": {"allow_anonymous": True}}
    options.update(plugins or {})
    broker = Broker({"listeners": {"default": {"type": "tcp", "bind": "127.0.0.1:0"}}, "plugins": options})
    await broker.start()
    try:
        port = broker._servers["default"].instance.sockets[0].getsockname()[1]
        print("aMQTT", version("amqtt"), "MQTT 3.1.1；仅本机回环")
        yield port
    finally:
        await broker.shutdown()


@asynccontextmanager
async def client(port, ident, username=None):
    reader, writer = await asyncio.open_connection("127.0.0.1", port)
    flags = 0x00 if username is None else 0x80
    body = string("MQTT") + bytes([4, flags, 0, 10]) + string(ident)
    if username is not None:
        body += string(username)
    try:
        assert len(body) < 128
        writer.write(bytes([0x10, len(body)]) + body)
        await writer.drain()
        ack = await asyncio.wait_for(reader.readexactly(4), 3)
        assert ack in (bytes.fromhex("20 02 00 00"), bytes.fromhex("20 02 01 00"))
        yield reader, writer
    finally:
        writer.close()
        await writer.wait_closed()


async def ping(connection):
    reader, writer = connection
    writer.write(bytes.fromhex("C0 00"))
    await writer.drain()
    assert await asyncio.wait_for(reader.readexactly(2), 3) == bytes.fromhex("D0 00")
