#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
magpie 模型全量可用性实测（2026-10-29）
方法论（继承 10-27 血泪）：
  - 不信 /v1/models catalog，只信真实 POST /v1/chat/completions 的 body
  - 必须看 body 内容，HTTP 200 可能返回 "OK"（github-models 前科）
  - 打本机网关必须绕过沙箱注入代理（ProxyHandler({})）
  - 组模型(group/*) 单测，组路由本身另测
"""
import json, sys, time, threading, urllib.request, urllib.error, socket
from concurrent.futures import ThreadPoolExecutor

GW = "http://127.0.0.1:3425"
TIMEOUT = 25
OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))  # 关键：禁用代理

_lock = threading.Lock()
_results = []


def probe(mid, stream=False):
    body = {
        "model": mid,
        "messages": [{"role": "user", "content": "reply with exactly: PONG"}],
        "max_tokens": 16,
    }
    if stream:
        body["stream"] = True
    data = json.dumps(body).encode("utf-8")
    req = urllib.request.Request(
        GW + "/v1/chat/completions", data=data,
        headers={"Content-Type": "application/json"})
    t0 = time.time()
    try:
        with OPENER.open(req, timeout=TIMEOUT) as r:
            raw = r.read()
            code = r.status
    except urllib.error.HTTPError as e:
        raw = e.read()
        code = e.code
    except Exception as e:
        return dict(model=mid, ok=False, code=0, ms=int((time.time() - t0) * 1000),
                    verdict="TIMEOUT/ERR", detail=f"{type(e).__name__}: {str(e)[:160]}")

    ms = int((time.time() - t0) * 1000)
    text = raw.decode("utf-8", "replace")
    r = dict(model=mid, ok=False, code=code, ms=ms, verdict="?", detail="", cost=None)
    try:
        j = json.loads(text)
    except Exception:
        r["verdict"] = "NON-JSON"
        r["detail"] = text[:160]
        return r
    # 有 error 字段
    if isinstance(j, dict) and j.get("error"):
        e = j["error"]
        msg = e.get("message") if isinstance(e, dict) else str(e)
        r["verdict"] = "ERROR"
        r["detail"] = str(msg)[:200]
        return r
    try:
        content = j["choices"][0]["message"]["content"]
    except Exception:
        r["verdict"] = "NO-CHOICE"
        r["detail"] = text[:160]
        return r
    if content is None or str(content).strip() == "":
        r["verdict"] = "EMPTY"
        r["detail"] = text[:160]
        return r
    # 真内容校验：PONG 命中最佳，但模型可能多说；只要非空且不是 OK 占位
    c = str(content).strip()
    if c.upper() in ("OK", "PONG OK"):
        r["verdict"] = "PLACEHOLDER-OK"
        r["detail"] = c[:120]
        return r
    r["ok"] = True
    r["verdict"] = "OK"
    r["content"] = c[:120]
    if isinstance(j, dict):
        r["cost"] = j.get("cost")
        u = j.get("usage")
        if isinstance(u, dict):
            r["tokens"] = u.get("total_tokens")
        cd = j.get("cost_details")
        if isinstance(cd, dict):
            r["upstream_cost"] = cd.get("upstream_inference_cost")
    return r


def main():
    cat = json.load(open("models_now.json", encoding="utf-8"))
    models = cat.get("data", [])
    ids = [m.get("id") for m in models if m.get("id")]
    # 组单独测（组路由流式会挂死，单测非流式）
    group_ids = [i for i in ids if i.startswith("group/")]
    plain = [i for i in ids if not i.startswith("group/")]

    print(f"catalog total={len(ids)}  plain={len(plain)}  groups={len(group_ids)}")
    print(f"probing {len(plain)} models, timeout={TIMEOUT}s, workers=8\n", flush=True)

    done = [0]

    def run(m):
        r = probe(m)
        with _lock:
            done[0] += 1
            _results.append(r)
            flag = "OK  " if r["ok"] else "FAIL"
            print(f"[{done[0]:3d}/{len(plain)}] {flag} {r['ms']:>7}ms {r['verdict']:<16} {r['model']}"
                  + (f"  | {r['detail'][:90]}" if not r["ok"] else f"  | {r.get('content','')[:60]}"), flush=True)

    with ThreadPoolExecutor(max_workers=8) as ex:
        list(ex.map(run, plain))

    print("\n--- groups (non-stream, direct) ---", flush=True)
    for g in group_ids:
        r = probe(g)
        print(f"  {r['verdict']:<16} {r['ms']:>7}ms {g}" + (f"  | {r['detail'][:90]}" if not r["ok"] else f"  | {r.get('content','')[:60]}"), flush=True)
        r["is_group"] = True
        _results.append(r)

    json.dump(_results, open("probe_results.json", "w", encoding="utf-8"),
              ensure_ascii=False, indent=1)
    ok = [r for r in _results if r["ok"]]
    print(f"\n==== SUMMARY: {len(ok)}/{len(_results)} usable ====")
    for r in sorted(ok, key=lambda x: x["model"]):
        cost = r.get("cost")
        print(f"  OK  {r['model']:60s} {r['ms']:>7}ms cost={cost}")


if __name__ == "__main__":
    main()
