# -*- coding: utf-8 -*-
"""
网关一键自检脚本(纯标准库,无需安装任何依赖)
================================================
用法:
    python 自检网关.py                          # 默认检测 http://192.168.201.96:8500/v1
    python 自检网关.py http://192.168.201.96:8500/v1
    python 自检网关.py http://127.0.0.1:8500/v1 123456

它会依次检查:
    1. 端口是否可连接
    2. GET  /v1          网关是否存活
    3. GET  /v1/health   配置是否真的加载了(upstream / 模型 / 密钥)
    4. POST /v1/chat/completions(非流式)  真正调用模型
    5. POST /v1/chat/completions(流式)
并把结果与排查建议打印出来。
"""
import sys
import json
import urllib.request
import urllib.error

DEFAULT_BASE = "http://192.168.201.96:8500/v1"


def show(title, ok, detail=""):
    mark = "OK  " if ok else "FAIL"
    print(f"[{mark}] {title}")
    if detail:
        for line in str(detail).splitlines()[:8]:
            print(f"        {line}")


def http(method, url, api_key=None, body=None, timeout=15):
    data = json.dumps(body).encode("utf-8") if body is not None else None
    req = urllib.request.Request(url, data=data, method=method)
    req.add_header("Content-Type", "application/json")
    if api_key:
        req.add_header("Authorization", f"Bearer {api_key}")
    with urllib.request.urlopen(req, timeout=timeout) as r:
        return r.status, r.read().decode("utf-8", "replace")


def main():
    base = (sys.argv[1] if len(sys.argv) > 1 else DEFAULT_BASE).rstrip("/")
    api_key = sys.argv[2] if len(sys.argv) > 2 else "123456"
    host_part = base.split("//", 1)[-1]

    print("=" * 64)
    print(f"网关自检:{base}")
    print("=" * 64)

    # 1) TCP 端口
    try:
        import socket
        hostport = host_part.split("/")[0]
        host, _, port = hostport.partition(":")
        port = int(port or 80)
        s = socket.socket()
        s.settimeout(5)
        rc = s.connect_ex((host, port))
        s.close()
        show(f"1. 端口 {host}:{port} 可连接", rc == 0,
             "" if rc == 0 else "连不上:网关没启动 / 防火墙拦截 / 网段不通(其他都是白搭,先解决这个)")
        if rc != 0:
            return
    except Exception as e:
        show("1. 端口检查", False, e)
        return

    # 2) /v1 存活
    try:
        st, txt = http("GET", base)
        show("2. GET /v1 网关存活", st == 200, f"{st} {txt[:160]}")
    except urllib.error.HTTPError as e:
        show("2. GET /v1 网关存活", False, f"HTTP {e.code} {e.read(200)}")
    except Exception as e:
        show("2. GET /v1 网关存活", False, e)

    # 3) /v1/health 配置是否加载
    config_ok = False
    try:
        st, txt = http("GET", base + "/health")
        j = json.loads(txt)
        config_ok = bool(j.get("config_loaded"))
        show("3. GET /v1/health 配置已加载", config_ok, txt[:300])
        if not config_ok:
            print("        提示:config_loaded=false 说明网关没读到 llm_config.json,"
                  "请确认网关与 llm_config.json 在同一目录、且已在网关界面点过【保存设置】")
    except Exception as e:
        show("3. GET /v1/health 配置已加载", False,
             f"{e}\n(若是 404,说明 .96 上还是旧版 AI中转.py,请把修复后的文件复制过去并重启网关)")

    # 4) 非流式对话
    payload = {"model": "deepseek-v4.1-flash",
               "messages": [{"role": "user", "content": "只回复两个字:收到"}],
               "stream": False, "max_tokens": 32}
    try:
        st, txt = http("POST", base + "/chat/completions", api_key, payload, timeout=90)
        ok = st == 200 and "choices" in txt
        show("4. POST 非流式对话", ok, f"{st} {txt[:300]}")
    except urllib.error.HTTPError as e:
        body = e.read().decode("utf-8", "replace")
        hint = ""
        if e.code == 401:
            hint = "→ 鉴权失败:WorkBuddy 里 apiKey 必须等于 .96 的 llm_config.json 中的 gateway_auth_key"
        elif e.code == 500:
            hint = "→ 网关内部错误:多为旧版代码或 base_url 未配置,请看 .96 的 gateway_logs.txt"
        elif e.code == 404:
            hint = "→ 路由不存在:.96 上可能是旧版 AI中转.py"
        show("4. POST 非流式对话", False, f"HTTP {e.code} {body[:300]}\n{hint}")
    except Exception as e:
        show("4. POST 非流式对话", False, e)

    # 5) 流式对话
    try:
        st, txt = http("POST", base + "/chat/completions", api_key,
                       {**payload, "stream": True}, timeout=90)
        ok = st == 200 and "data:" in txt
        show("5. POST 流式对话", ok, f"{st} 收到 {len(txt)} 字节 SSE")
    except Exception as e:
        show("5. POST 流式对话", False, e)

    print("-" * 64)
    print("全部 OK → 到 WorkBuddy 选【网关(192.168.201.96:8500)】这条模型即可正常对话。")
    print("若有 FAIL,按上面每一项后面的提示处理。")


if __name__ == "__main__":
    main()