"""Opik 로컬 중계 — 127.0.0.1:15173 → 192.168.133.87:5173.

★왜 있나 (2026-09-17): macOS 「로컬 네트워크」 권한이 홈브루 Python
 (`/opt/homebrew/.../Python.app`) 에서 꺼져 있어, 백엔드가 LAN 의 Opik 에
 `Errno 65 No route to host` 로 못 붙었다. 시스템 Python(/usr/bin/python3)과
 curl 은 붙는다. Opik 에 이 기계 기록이 09-09 20:35 KST 이후 0건이었다.

 권한을 켜면(시스템 설정 → 개인정보 보호 및 보안 → 로컬 네트워크 → Python)
 이 중계는 필요 없다 — 그때 `.env` 의 OPIK_URL_OVERRIDE 를 원래 주소로 되돌린다.

반드시 **/usr/bin/python3** 로 띄운다(홈브루 Python 으로 띄우면 똑같이 막힌다).
"""
import asyncio, sys

LISTEN = ("127.0.0.1", 15173)
TARGET = ("192.168.133.87", 5173)


async def pipe(r, w):
    try:
        while True:
            b = await r.read(65536)
            if not b:
                break
            w.write(b)
            await w.drain()
    except Exception:
        pass
    finally:
        try:
            w.close()
        except Exception:
            pass


async def handle(cr, cw):
    try:
        tr, tw = await asyncio.wait_for(asyncio.open_connection(*TARGET), 10)
    except Exception as ex:
        print(f"target 연결 실패: {ex}", file=sys.stderr, flush=True)
        cw.close()
        return
    await asyncio.gather(pipe(cr, tw), pipe(tr, cw))


async def main():
    srv = await asyncio.start_server(handle, *LISTEN)
    print(f"relay {LISTEN} → {TARGET}", flush=True)
    async with srv:
        await srv.serve_forever()

asyncio.run(main())
