#!/bin/bash
# Test the OpenCode chat endpoint through several cache-clean exit IPs.
export LC_ALL=C
LIST=/tmp/oc_links.txt
[ -s "$LIST" ] || { echo "no link list"; exit 1; }

python3 - "$LIST" <<'PY'
import json, os, subprocess, sys, time, importlib.util
import urllib.request
from concurrent.futures import ThreadPoolExecutor

spec = importlib.util.spec_from_file_location("proxylab", "/opt/proxy-lab/proxylab.py")
pl = importlib.util.module_from_spec(spec); spec.loader.exec_module(pl)

links = [l.strip() for l in open(sys.argv[1], encoding="utf-8") if l.strip()]
parsed = []
for ln in links:
    try:
        ob, _ = pl.parse_link(ln)
        parsed.append((ln, ob))
    except Exception:
        pass
print(f"parsed {len(parsed)}/{len(links)}")

BASE = 22600
cfg = {"log": {"level": "error"},
       "dns": {"servers": [{"type": "local", "tag": "local"}]},
       "inbounds": [], "outbounds": [{"type": "direct", "tag": "direct"}],
       "route": {"rules": [], "final": "direct", "default_domain_resolver": "local"}}
for i, (_, ob) in enumerate(parsed):
    o = dict(ob); o["tag"] = f"o{i}"; cfg["outbounds"].append(o)
    cfg["inbounds"].append({"type": "mixed", "tag": f"i{i}", "listen": "127.0.0.1", "listen_port": BASE+i})
    cfg["route"]["rules"].append({"inbound": [f"i{i}"], "outbound": f"o{i}"})

p = "/tmp/oc_multi.json"
json.dump(cfg, open(p, "w"))
proc = subprocess.Popen(["/opt/proxy-lab/bin/sing-box", "run", "-c", p],
                        stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
time.sleep(4)

BODY = json.dumps({"model": "mimo-v2.6-flash-free",
                   "messages": [{"role": "user", "content": "hi"}],
                   "stream": True}).encode()

def test(i):
    port = BASE + i
    proxy = urllib.request.ProxyHandler({"http": f"http://127.0.0.1:{port}",
                                         "https": f"http://127.0.0.1:{port}"})
    op = urllib.request.build_opener(proxy)
    req = urllib.request.Request("https://opencode.ai/zen/v1/chat/completions", data=BODY,
                                 headers={"content-type": "application/json",
                                          "accept": "text/event-stream",
                                          "x-opencode-client": "desktop"})
    t0 = time.time()
    try:
        with op.open(req, timeout=25) as r:
            body = r.read(160).decode("utf-8", "replace")
            return i, r.status, int((time.time()-t0)*1000), body
    except urllib.error.HTTPError as e:
        return i, e.code, int((time.time()-t0)*1000), e.read(160).decode("utf-8", "replace")
    except Exception as e:
        return i, 0, int((time.time()-t0)*1000), str(e)[:80]

try:
    with ThreadPoolExecutor(max_workers=8) as ex:
        results = list(ex.map(test, range(len(parsed))))
finally:
    proc.terminate()

print("\n  st   ms    exit-server                        body")
for i, code, ms, body in sorted(results, key=lambda r: (r[1] != 200, r[2])):
    ob = parsed[i][1]
    host = f"{ob.get('server')}:{ob.get('server_port')}"
    print(f"  {code:<4} {ms:<5} {host:<32} {body[:90].strip()}")
PY
