#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Groq 出口节点体检（2026-10-29）
背景（实测结论）：
  - Groq 请求必须带 User-Agent，否则 Cloudflare 返 1010 拦截
  - 带 UA 后 Groq 应用层仍按出口 IP 放行：Türkiye→OK，China→403，意大利/英国→SSL EOF（节点坏）
  - Hiddify 的 select→balance 是 24 节点轮换，所以每连接出口都变
目的：逐个测 24 个节点，找出 Groq 稳定可用的节点，供「钉出口」用。
方法：Clash API 切换 select 到某节点 → 用该节点出口打 Groq → 记录结果。
"""
import json, urllib.request, urllib.error, time, sys

CLASH = "http://127.0.0.1:16756"
SECRET = "bMiytQcrbg926jiR"
PROXY = "http://127.0.0.1:12334"
CHROME = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
          "(KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36")
OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))


def clash(path, method="GET", body=None):
    req = urllib.request.Request(
        CLASH + path,
        data=json.dumps(body).encode() if body else None,
        headers={"Authorization": "Bearer " + SECRET, "Content-Type": "application/json"},
        method=method)
    try:
        with OPENER.open(req, timeout=12) as r:
            return r.status, r.read()
    except urllib.error.HTTPError as e:
        return e.code, e.read()[:200]
    except Exception as e:
        return 0, str(e).encode()


def groq_call(model="qwen/qwen3.8-27b", timeout=25):
    """经 Hiddify 代理打 Groq（带 UA），返回 (verdict, 出口IP)"""
    d = json.loads(open(r"C:\Users\ngmk\.config\magpie\providers.json",
                        encoding="utf-8", errors="replace").read())
    gk = [p for p in d.get("providers", []) if p.get("id") == "groq"][0]["key"]
    body = json.dumps({"model": model,
                       "messages": [{"role": "user", "content": "reply PONG"}],
                       "max_tokens": 16}).encode()
    h = {"Content-Type": "application/json", "Authorization": "Bearer " + gk,
         "User-Agent": CHROME}
    opener = urllib.request.build_opener(
        urllib.request.ProxyHandler({"http": PROXY, "https": PROXY}))
    # 先取出口 IP
    ip = "n/a"
    try:
        with opener.open("http://ip-api.com/line/?fields=query,country", timeout=12) as x:
            ip = x.read().decode("utf-8", "replace").strip().replace("\n", " ")
    except Exception:
        pass
    req = urllib.request.Request("https://api.groq.com/openai/v1/chat/completions",
                                 data=body, headers=h)
    try:
        with opener.open(req, timeout=timeout) as x:
            j = json.loads(x.read())
            c = (j["choices"][0]["message"].get("content") or "").strip()
            return ("OK" if c else "EMPTY"), ip
    except urllib.error.HTTPError as e:
        t = e.read().decode("utf-8", "replace")
        if "1010" in t:
            return "CF1010", ip
        if "Access denied" in t:
            return "DENIED", ip
        return "HTTP%d" % e.code, ip
    except urllib.error.URLError as e:
        return "NETERR", ip
    except Exception as e:
        return "ERR:" + type(e).__name__, ip


def main():
    c, b = clash("/proxies/select")
    if c != 200:
        print("Clash API 不可用:", c, b[:120]); return
    sel = json.loads(b)
    if "proxies" in sel:
        sel = sel["proxies"]["select"]
    nodes = [x for x in (sel.get("all") or [])
             if x not in ("lowest", "balance")]
    orig = sel.get("now")
    print(f"select 当前 = {orig}，待测节点 {len(nodes)} 个\n")

    results = []
    for n in nodes:
        c, b = clash("/proxies/select", "PUT", {"name": n})
        if c not in (200, 204):
            print(f"  {n[:44]:46s} 切换失败 HTTP{c}")
            continue
        time.sleep(2.5)          # 等连接池/路由生效
        v, ip = groq_call()
        results.append({"node": n, "verdict": v, "ip": ip})
        print(f"  {n[:44]:46s} {v:8s} ip={ip}")
        time.sleep(1.0)

    # 还原
    clash("/proxies/select", "PUT", {"name": orig})
    print(f"\n已还原 select = {orig}")

    ok = [r for r in results if r["verdict"] == "OK"]
    print(f"\n==== Groq 可用节点: {len(ok)}/{len(results)} ====")
    for r in ok:
        print(f"  OK  {r['node']:46s} ip={r['ip']}")
    json.dump(results, open("groq_node_probe.json", "w", encoding="utf-8"),
              ensure_ascii=False, indent=1)


if __name__ == "__main__":
    main()
