#!/usr/bin/env python3
"""Interop fixture: a Python Reticulum node that announces over a TCP server.

Used by the plexus live-interop test (crates/plexus-iface/tests/). Runs an RNS
instance with a TCPServerInterface on a given port, creates a deterministic
destination, and announces it once per second. Prints `DEST <hex>` on stdout so
the connecting test knows which destination to expect.

    announce_server.py <port>
"""

import os
import sys
import tempfile
import time


def main() -> None:
    port = int(sys.argv[1])
    cfg = tempfile.mkdtemp()
    with open(os.path.join(cfg, "config"), "w") as f:
        f.write(
            "[reticulum]\n"
            "  enable_transport = True\n"
            "  share_instance = False\n"
            "  panic_on_interface_error = False\n"
            "[logging]\n"
            "  loglevel = 2\n"
            "[interfaces]\n"
            "  [[TCP Server]]\n"
            "    type = TCPServerInterface\n"
            "    interface_enabled = True\n"
            "    listen_ip = 127.0.0.1\n"
            f"    listen_port = {port}\n"
        )

    import RNS

    RNS.Reticulum(configdir=cfg)
    ident = RNS.Identity(create_keys=False)
    ident.load_private_key(bytes(range(64)))
    dest = RNS.Destination(
        ident, RNS.Destination.IN, RNS.Destination.SINGLE, "plexus", "interop"
    )
    print("DEST " + dest.hash.hex(), flush=True)

    # Report announces we receive for "plexus.emit" — the plexus send-interop
    # test announces under that name. RNS validates the signature before calling
    # the handler, so a RECV line means the reference accepted our announce.
    class _Handler:
        aspect_filter = "plexus.emit"

        def received_announce(self, destination_hash, announced_identity, app_data, **kwargs):
            data = app_data.hex() if app_data else ""
            print("RECV " + destination_hash.hex() + " " + data, flush=True)

    RNS.Transport.register_announce_handler(_Handler())

    while True:
        dest.announce(app_data=b"interop")
        time.sleep(1)


if __name__ == "__main__":
    main()
