# -*- coding: utf-8 -*-
"""
magpie Groq 出口钉节点自愈（2026-10-29）

背景：
  Hiddify 的 select 组默认指向 balance（24 节点轮换），每条连接的出口 IP 都不同。
  Groq 的 Cloudflare + 应用层双重要求：
    ① 请求必须带 User-Agent（否则 CF 返 1010）
    ② 出口 IP 必须在 Groq 放行名单（实测 13/24 节点可用，意大利节点最稳）
  轮换到被拒节点时 Groq 表现为 "Access denied" / CF1010，间歇性全挂。

本脚本：把 Hiddify 的 select 组钉到实测可用的固定节点，并在节点失效时自动回退到下一个可用节点。
只依赖 Python 标准库。

部署：计划任务动作 = pythonw.exe <本文件>（无控制台窗口）
"""
import json
import os
import time
import urllib.request
import urllib.error
from datetime import datetime

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")

# 实测可用的节点（2026-09-29 逐节点探测：13/24 OK，意大利节点最密集）
# 完整结果见 groq_node_probe.json
PREFERRED = [
    "IT 🇮🇹 | @Raydikalx | 8B9F9D § 9",
    "IT 🇮🇹 | @Raydikalx | 8DCE34 § 10",
    "IT 🇮🇹 | @Raydikalx | 075327 § 11",
    "IT 🇮🇹 | @Raydikalx | 42A105 § 12",
    "IT 🇮🇹 | @Raydikalx | 982F42 § 13",
    "IT 🇮🇹 | @Raydikalx | ED56A4 § 16",
    "IT 🇮🇹 | @Raydikalx | BB8168 § 18",
    "IT 🇮🇹 | @Raydikalx | 3FA46F § 19",
    "IT 🇮🇹 | @Raydikalx | 9453B9 § 21",
    "US 🇺🇸 | @Raydikalx | CD0CE3 § 8",
    "US 🇺🇸 | @Raydikalx | B10F48 § 15",
    "DE 🇩🇪 | @Raydikalx | 4591B3 § 23",
]
# 备用池：其他实测 OK 的节点
FALLBACK = [
    "IL 🇮🇱 | @Raydikalx | 403872 § 14",
]

LOG = r"D:\magpie\groq_exit_pin.log"
STATE = r"D:\magpie\.groq_pin_state"
_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))


def log(msg):
    try:
        # utf-8-sig：写 BOM，PowerShell Get-Content 能正确显示中文（不带 BOM 会乱码）
        with open(LOG, "a", encoding="utf-8-sig") as f:
            f.write("[%s] %s\n" % (datetime.now().strftime("%Y-%m-%d %H:%M:%S"), msg))
    except Exception:
        pass


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_ok(timeout=25):
    """经当前出口打 Groq（带 UA），返回 True=通"""
    try:
        cfg = json.loads(open(r"C:\Users\ngmk\.config\magpie\providers.json",
                             encoding="utf-8", errors="replace").read())
    except Exception:
        return False
    gk = None
    for p in cfg.get("providers", []):
        if p.get("id") == "groq":
            gk = p.get("key")
    if not gk:
        return False
    body = json.dumps({"model": "qwen/qwen3.8-27b",
                       "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}))
    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 bool(c)
    except Exception:
        return False


def read_state():
    try:
        return open(STATE, encoding="utf-8").read().strip()
    except Exception:
        return ""


def write_state(v):
    try:
        open(STATE, "w", encoding="utf-8").write(v)
    except Exception:
        pass


def main():
    c, b = clash("/proxies/select")
    if c != 200:
        log("Clash API 不可用 HTTP=%s" % c)
        return
    try:
        sel = json.loads(b)
        if "proxies" in sel:
            sel = sel["proxies"]["select"]
    except Exception:
        return
    cur = sel.get("now")
    state = read_state()

    # 已经钉在已知可用节点上，且上次是通的 -> 只做轻量复核
    if cur in PREFERRED and state == cur:
        if groq_ok():
            log("复核通过，出口仍钉在: %s" % cur)
            return
        log("当前节点 %s 复核失败，尝试切换" % cur)

    # 依次尝试：当前钉的 -> PREFERRED -> FALLBACK
    order = []
    if cur in PREFERRED:
        order.append(cur)
    order += [n for n in PREFERRED if n != cur]
    order += FALLBACK

    for node in order:
        c, _ = clash("/proxies/select", "PUT", {"name": node})
        if c not in (200, 204):
            continue
        time.sleep(3)
        if groq_ok():
            log("已钉到可用节点: %s" % node)
            write_state(node)
            return
        log("节点 %s 不通，继续下一个" % node)

    log("所有候选节点均不通，保留当前 select=%s" % cur)


if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        log("异常: %s: %s" % (type(e).__name__, e))
