#!/usr/bin/env python3
"""LAN bridge: receive ESP32 RuView UDP/5005 frames and tunnel them over WSS."""
import asyncio, base64, json, os, signal, socket
import websockets

GATEWAY = os.environ.get('CYBERNET_GATEWAY', '').rstrip('/')
TOKEN = os.environ.get('EDGE_INGEST_TOKEN', '')
LISTEN = os.environ.get('CSI_LISTEN', '0.0.0.0')
PORT = int(os.environ.get('CSI_PORT', '5005'))

class Relay(asyncio.DatagramProtocol):
    def __init__(self): self.queue = asyncio.Queue(maxsize=2000); self.dropped = 0
    def datagram_received(self, data, addr):
        if self.queue.full():
            self.dropped += 1
            try: self.queue.get_nowait()
            except asyncio.QueueEmpty: pass
        self.queue.put_nowait(data)

async def run():
    if not GATEWAY.startswith('https://') or not TOKEN:
        raise SystemExit('Set CYBERNET_GATEWAY=https://... and EDGE_INGEST_TOKEN.')
    relay = Relay(); loop = asyncio.get_running_loop()
    transport, _ = await loop.create_datagram_endpoint(lambda: relay, local_addr=(LISTEN, PORT))
    uri = GATEWAY.replace('https://', 'wss://', 1) + '/edge/ingest'
    try:
        while True:
            try:
                async with websockets.connect(uri, additional_headers={'Authorization': 'Bearer ' + TOKEN}, ping_interval=20, ping_timeout=20, max_size=65536) as ws:
                    print(f'Connected; forwarding UDP {LISTEN}:{PORT} to CyberNet gateway')
                    while True:
                        packet = await relay.queue.get()
                        await ws.send(json.dumps({'type':'csi','data':base64.b64encode(packet).decode()}))
            except (OSError, websockets.WebSocketException) as e:
                print(f'Tunnel disconnected: {e}; retrying in 3s')
                await asyncio.sleep(3)
    finally: transport.close()

if __name__ == '__main__': asyncio.run(run())
