#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
magpie 第二轮复测（2026-10-29）
针对第一轮的三类假阴性：
  1) EMPTY  -> reasoning_content 吃光了 max_tokens=16，改用 256 重测
  2) TIMEOUT-> NIM/auto 组模型可能只是慢，串行 + 60s 重测
  3) OK但内容不像PONG -> 可能是内容安全分类模型（非聊天模型），二次确认
判可用 = 200 + 合法JSON + content非空
"""
import json, time, urllib.request, urllib.error
from concurrent.futures import ThreadPoolExecutor

GW = "http://127.0.0.1:3425"
OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))

EMPTY_1ST = [
    "auto/qwen3.8-27b", "intern-tokenplan/Agents-A1", "auto/glm-5.3",
    "intern-tokenplan/Sage-A1.5", "intern-tokenplan/glm-5.3",
    "intern-tokenplan/kimi-k2.6", "intern-tokenplan/minimax-m3",
    "intern-tokenplan/qwen3.8-27b", "intern-tokenplan/intern-s2",
    "nvidia/google/diffusiongemma-26b-a4b-it",
    "groq/openai/gpt-oss-20b", "groq/openai/gpt-oss-safeguard-20b",
    "groq/openai/gpt-oss-120b", "group/hermes", "group/free-chain",
]
TIMEOUT_1ST = [
    "auto/deepseek-v4.1-flash", "auto/gemma-4-31b-it", "auto/gemini-3.8-flash",
    "nvidia/deepseek-ai/deepseek-v4.1-flash", "nvidia/google/gemma-4-31b-it",
]
SUSPECT = [
    "groq/meta-llama/llama-prompt-guard-2-22m",
    "groq/meta-llama/llama-prompt-guard-2-86m",
    "groq/allam-2-7b",
]


def probe(mid, timeout=60, max_tokens=256, prompt="reply with exactly: PONG"):
    body = {"model": mid, "messages": [{"role": "user", "content": prompt}],
            "max_tokens": max_tokens}
    req = urllib.request.Request(GW + "/v1/chat/completions",
                                 data=json.dumps(body).encode("utf-8"),
                                 headers={"Content-Type": "application/json"})
    t0 = time.time()
    try:
        with OPENER.open(req, timeout=timeout) as r:
            raw, code = r.read(), r.status
    except urllib.error.HTTPError as e:
        raw, code = e.read(), 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)[:150]}")
    ms = int((time.time()-t0)*1000)
    text = raw.decode("utf-8", "replace")
    try:
        j = json.loads(text)
    except Exception:
        return dict(model=mid, ok=False, code=code, ms=ms, verdict="NON-JSON", detail=text[:120])
    if isinstance(j, dict) and j.get("error"):
        e = j["error"]
        return dict(model=mid, ok=False, code=code, ms=ms, verdict="ERROR",
                    detail=str(e.get("message") if isinstance(e, dict) else e)[:200])
    try:
        msg = j["choices"][0]["message"]
        content = msg.get("content")
        reasoning = msg.get("reasoning_content") or ""
    except Exception:
        return dict(model=mid, ok=False, code=code, ms=ms, verdict="NO-CHOICE", detail=text[:150])
    c = (content or "").strip()
    if not c:
        return dict(model=mid, ok=False, code=code, ms=ms, verdict="EMPTY",
                    detail=f"reasoning_only({len(reasoning)}ch): {reasoning[:110]}")
    if c.upper() in ("OK", "PONG OK"):
        return dict(model=mid, ok=False, code=code, ms=ms, verdict="PLACEHOLDER-OK", detail=c[:100])
    return dict(model=mid, ok=True, code=code, ms=ms, verdict="OK", content=c[:200],
                reasoning=(reasoning or "")[:80],
                cost=j.get("cost") if isinstance(j, dict) else None,
                tokens=(j.get("usage") or {}).get("total_tokens"))


def run(mid, timeout, mt):
    r = probe(mid, timeout=timeout, max_tokens=mt)
    tag = "OK  " if r["ok"] else "FAIL"
    print(f"  {tag} {r['ms']:>7}ms {r['verdict']:<16} {r['model']}"
          + (f"  | {r.get('content','')[:70]}" if r["ok"] else f"  | {r['detail'][:100]}"), flush=True)
    return r


if __name__ == "__main__":
    out = []
    print("=== A. EMPTY 复测 (max_tokens=256, timeout=60) ===", flush=True)
    with ThreadPoolExecutor(max_workers=5) as ex:
        out += list(ex.map(lambda m: run(m, 60, 256), EMPTY_1ST))

    print("\n=== B. TIMEOUT 复测 (串行, timeout=90) ===", flush=True)
    for m in TIMEOUT_1ST:
        out.append(run(m, 90, 256))

    print("\n=== C. 可疑模型二次确认（问个实际问题，验证是否真聊天模型）===", flush=True)
    for m in SUSPECT:
        r = probe(m, timeout=60, max_tokens=256, prompt="What is 2+2? Answer with the number only.")
        print(f"  {'OK  ' if r['ok'] else 'FAIL'} {r['ms']:>7}ms {r['verdict']:<16} {r['model']}"
              + (f"  | {r.get('content','')[:110]}" if r["ok"] else f"  | {r['detail'][:100]}"), flush=True)
        r["suspect"] = True
        out.append(r)

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