#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
group/verified 端到端验收（2026-10-29）
10-27 血泪：组路由 + streaming 会挂死；组路由与单模型直打行为不同。
三档验收：非流式 / 流式 / 长提示词(~12K token，模拟 Hermes 真实负载)
每档都看 body 真内容 + 落点（served model）
"""
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({}))
GROUP = "group/verified"


def nonstream(mid, timeout=90, prompt="reply with exactly: PONG", max_tokens=64):
    body = json.dumps({"model": mid, "messages": [{"role": "user", "content": prompt}],
                       "max_tokens": max_tokens}).encode("utf-8")
    req = urllib.request.Request(GW + "/v1/chat/completions", data=body,
                                 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(kind="nonstream", ok=False, ms=int((time.time()-t0)*1000),
                    verdict="TIMEOUT/ERR", detail=f"{type(e).__name__}: {str(e)[:120]}")
    ms = int((time.time()-t0)*1000)
    text = raw.decode("utf-8", "replace")
    try:
        j = json.loads(text)
    except Exception:
        return dict(kind="nonstream", ok=False, ms=ms, verdict="NON-JSON", detail=text[:120])
    if isinstance(j, dict) and j.get("error"):
        return dict(kind="nonstream", ok=False, ms=ms, verdict="ERROR",
                    detail=str(j["error"])[:180])
    try:
        c = (j["choices"][0]["message"].get("content") or "").strip()
    except Exception:
        return dict(kind="nonstream", ok=False, ms=ms, verdict="NO-CHOICE", detail=text[:150])
    if not c:
        rc = (j["choices"][0]["message"].get("reasoning_content") or "")[:100]
        return dict(kind="nonstream", ok=False, ms=ms, verdict="EMPTY",
                    detail=f"reasoning_only: {rc}")
    return dict(kind="nonstream", ok=True, ms=ms, verdict="OK", content=c[:100],
                served=j.get("model"), cost=j.get("cost"))


def stream(mid, timeout=90, prompt="reply with exactly: PONG", max_tokens=64):
    body = json.dumps({"model": mid, "messages": [{"role": "user", "content": prompt}],
                       "max_tokens": max_tokens, "stream": True}).encode("utf-8")
    req = urllib.request.Request(GW + "/v1/chat/completions", data=body,
                                 headers={"Content-Type": "application/json"})
    t0 = time.time()
    chunks, got_done, txt = 0, False, ""
    try:
        with OPENER.open(req, timeout=timeout) as r:
            for raw in r:
                line = raw.decode("utf-8", "replace").strip()
                if not line.startswith("data:"):
                    continue
                chunks += 1
                data = line[5:].strip()
                if data == "[DONE]":
                    got_done = True
                    break
                try:
                    j = json.loads(data)
                    for ch in (j.get("choices") or []):
                        c = (ch.get("delta") or {}).get("content")
                        if c:
                            txt += c
                except Exception:
                    pass
        ms = int((time.time()-t0)*1000)
        if got_done and txt.strip():
            return dict(kind="stream", ok=True, ms=ms, verdict="STREAM-OK",
                        content=txt.strip()[:80], chunks=chunks)
        return dict(kind="stream", ok=False, ms=ms, verdict="DONE-NO-TEXT" if got_done else "NO-DONE",
                    detail=f"chunks={chunks} done={got_done} text={txt[:60]!r}")
    except Exception as e:
        return dict(kind="stream", ok=False, ms=int((time.time()-t0)*1000),
                    verdict="TIMEOUT/ERR", detail=f"{type(e).__name__}: {str(e)[:120]}")


def longprompt(mid, timeout=120):
    """模拟 Hermes 的 ~12K token 系统提示词负载"""
    filler = ("The following is a long context block for load testing purposes. " * 260)
    return nonstream(mid, timeout=timeout,
                     prompt=filler + "\n\nreply with exactly: PONG", max_tokens=32)


if __name__ == "__main__":
    print(f"=== 验收 {GROUP} ===\n", flush=True)

    print("A. 非流式 x3（路由稳定性）", flush=True)
    for i in range(3):
        r = nonstream(GROUP)
        print(f"  {'OK  ' if r['ok'] else 'FAIL'} #{i+1} {r['ms']:>7}ms {r['verdict']:<14}"
              + (f" served={r.get('served')} content={r.get('content','')[:50]!r}" if r["ok"]
                 else f"  | {r.get('detail','')[:100]}"), flush=True)

    print("\nB. 流式 x2（10-27 挂死点）", flush=True)
    for i in range(2):
        r = stream(GROUP)
        print(f"  {'OK  ' if r['ok'] else 'FAIL'} #{i+1} {r['ms']:>7}ms {r['verdict']:<14}"
              + (f" chunks={r.get('chunks')} content={r.get('content','')[:50]!r}" if r["ok"]
                 else f"  | {r.get('detail','')[:100]}"), flush=True)

    print("\nC. 长提示词 ~12K token（Hermes 真实负载）", flush=True)
    r = longprompt(GROUP)
    print(f"  {'OK  ' if r['ok'] else 'FAIL'} {r['ms']:>7}ms {r['verdict']:<14}"
          + (f" served={r.get('served')}" if r["ok"] else f"  | {r.get('detail','')[:120]}"), flush=True)

    print("\nD. 单成员直打对照（组路由是否吞掉能力）", flush=True)
    for m in ["intern-tokenplan/deepseek-v4-pro-0813", "groq/openai/gpt-oss-120b"]:
        r = nonstream(m)
        print(f"  {'OK  ' if r['ok'] else 'FAIL'} {r['ms']:>7}ms {m} "
              + (f"served={r.get('served')} cost={r.get('cost')}" if r["ok"]
                 else f"| {r.get('detail','')[:90]}"), flush=True)
