"""SenseNova API 连通性测试 — 无交互版，直接用 http_request 工具替代"""
import json, sys, urllib.request, urllib.error

BASE_URL = "https://api.sensenova.cn/compatible-mode/v1"

# 从命令行参数读 key 和 model
API_KEY = sys.argv[1] if len(sys.argv) > 1 else ""
MODEL = sys.argv[2] if len(sys.argv) > 2 else "SenseNova-Turbo"

if not API_KEY:
    print("ERROR: 用法: python test_sensenova.py <api_key> [model_name]")
    sys.exit(1)

print(f"Base URL : {BASE_URL}")
print(f"Model    : {MODEL}")
print(f"API Key  : {API_KEY[:6]}...{API_KEY[-3:]}")
print("-" * 50)

# 测试 1: chat/completions
print("[1/2] chat/completions ...")
url = f"{BASE_URL}/chat/completions"
payload = json.dumps({
    "model": MODEL,
    "messages": [{"role": "user", "content": "hi"}],
    "max_tokens": 16,
    "stream": False,
}).encode("utf-8")

req = urllib.request.Request(url, data=payload, method="POST")
req.add_header("Content-Type", "application/json")
req.add_header("Authorization", f"Bearer {API_KEY}")

try:
    with urllib.request.urlopen(req, timeout=20) as resp:
        body = json.loads(resp.read().decode("utf-8"))
        content = body.get("choices", [{}])[0].get("message", {}).get("content", "")
        print(f"  OK! reply: {content}")
except urllib.error.HTTPError as e:
    print(f"  FAIL HTTP {e.code}: {e.read().decode('utf-8')}")
except Exception as e:
    print(f"  FAIL: {e}")

# 测试 2: models
print("[2/2] models list ...")
url2 = f"{BASE_URL}/models"
req2 = urllib.request.Request(url2, method="GET")
req2.add_header("Authorization", f"Bearer {API_KEY}")
try:
    with urllib.request.urlopen(req2, timeout=15) as resp:
        body = json.loads(resp.read().decode("utf-8"))
        models = body.get("data", [])
        print(f"  OK! {len(models)} models:")
        for m in models[:10]:
            print(f"    - {m.get('id', '?')}")
except urllib.error.HTTPError as e:
    print(f"  FAIL HTTP {e.code}: {e.read().decode('utf-8')}")
except Exception as e:
    print(f"  FAIL: {e}")

print("-" * 50)
print("Done.")
