#!/usr/bin/env python3
import json
import time
import urllib.parse
import urllib.request

BASE = "http://127.0.0.1:9090"


def wait_api(retries=15):
    for _ in range(retries):
        try:
            with urllib.request.urlopen(BASE + "/proxies", timeout=3) as r:
                return json.loads(r.read())
        except Exception:
            time.sleep(1)
    raise SystemExit("clash api not ready")


def put_proxy(group: str, target: str):
    enc_g = urllib.parse.quote(group, safe="")
    req = urllib.request.Request(
        BASE + "/proxies/" + enc_g,
        data=json.dumps({"name": target}).encode(),
        method="PUT",
        headers={"Content-Type": "application/json"},
    )
    with urllib.request.urlopen(req, timeout=5) as r:
        print("switched", group, "->", target, "status", r.status)


def main():
    data = wait_api()
    proxies = data.get("proxies", {})
    group = None
    for gname in ["🚀节点选择", "GLOBAL"]:
        if gname in proxies:
            group = gname
            break
    if not group:
        raise SystemExit("selector group not found")

    print("group=", group, "now=", proxies.get(group, {}).get("now"))

    candidates = [
        "🇸🇬狮城节点",
        "🇸🇬AWS新加坡01 | 电信移动联通推荐",
        "🇸🇬新加坡01 | 电信联通推荐",
        "🇸🇬新加坡 | 高速专线-hy2",
    ]
    target = next((c for c in candidates if c in proxies), None)
    if not target:
        for k in proxies:
            if "新加坡" in k or "AWS新加坡" in k:
                target = k
                break
    if not target:
        raise SystemExit("no SG proxy found")

    put_proxy(group, target)

    enc_g = urllib.parse.quote(group, safe="")
    with urllib.request.urlopen(BASE + "/proxies/" + enc_g, timeout=3) as r:
        print("verify now=", json.loads(r.read()).get("now"))


if __name__ == "__main__":
    main()
