import json, time, urllib.request, urllib.error, http.cookiejar

MGR = "http://127.0.0.1:19088"
IID = "friend-99e81e37"
ADMIN = {"Authorization": "Bearer dev-admin-token"}

def mgr(path, method="GET", body=None):
    req = urllib.request.Request(MGR + path, method=method,
        data=json.dumps(body).encode() if body else None,
        headers={**ADMIN, "Content-Type": "application/json"})
    return json.loads(urllib.request.urlopen(req, timeout=30).read())

# create tunnel
t = mgr(f"/api/v1/instances/{IID}/tunnels", "POST", {})
token = t.get("token") or (t.get("tunnel") or {}).get("token")
if not token and t.get("url") and "__friend_tunnel=" in t["url"]:
    token = t["url"].split("__friend_tunnel=")[1].split("&")[0]
print("tunnel:", (token or "")[:12])

cj = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))

def panel(path, method="GET", body=None):
    req = urllib.request.Request(f"{MGR}/panel/{IID}{path}", method=method,
        data=json.dumps(body).encode() if body is not None else None,
        headers={"Content-Type": "application/json", "Cookie": f"friend_cluster_tunnel={token}"})
    try:
        r = opener.open(req, timeout=30)
        return r.status, r.read().decode()
    except urllib.error.HTTPError as e:
        return e.code, e.read().decode()

# 1. push service-proxy/llm-proxy config (friend_go expects {"config": {...}} wrapper)
code, resp = panel("/api/plugins/llm-proxy/config", "PUT", {"config": {
    "upstream_base": "http://10.200.0.20:3000",
    "api_key": "sk-m2ZMH0W1EYSL4vrXwE0WjvQTSOKhhX4oMp31zZskZ6xDPl96",
    "listen_addr": "127.0.0.1:39527",
}})
print("proxy config:", code, resp[:100])

time.sleep(3)

# 2. sync models
code, resp = panel("/api/llm/channels/1/sync-models", "POST", {})
print("sync:", code, resp[:120])

# 3. list models
code, resp = panel("/api/llm/models")
models = json.loads(resp)
if isinstance(models, dict):
    models = models.get("models", [])
print("models:", len(models))
for m in models[:12]:
    print(" ", m.get("id"), m.get("model_key"), m.get("health_status"))

# 4. clear cooldown + probe all
for m in models:
    mid = m.get("id")
    panel(f"/api/llm/models/{mid}/clear-cooldown", "POST", {})
time.sleep(2)
for m in models:
    mid = m.get("id")
    code, resp = panel(f"/api/llm/models/{mid}/probe", "POST", {})
    try:
        d = json.loads(resp)
        print("probe", mid, m.get("model_key"), "->", d.get("health_status") or d.get("status") or resp[:60])
    except Exception:
        print("probe", mid, code, resp[:60])
