#!/usr/bin/env python3
"""测试在 user 消息后插入 system 消息是否会被转换"""

import os
import json
import requests
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

# 获取 Kimi 官方 API 配置（请通过环境变量提供）
api_key = os.getenv("MOONSHOT_API_KEY", "")
# 使用 Kimi 官方 API
api_base = os.getenv("MOONSHOT_API_BASE", "https://api.moonshot.cn/v1")

if not api_key:
    raise SystemExit("请先设置环境变量 MOONSHOT_API_KEY")

# 构建测试消息
messages = [
    {
        "role": "system",
        "content": "你是一个AI助手。"
    },
    {
        "role": "user",
        "content": "请帮我看看我这句话后面的那条testcode消息的角色是system还是user"
    },
    {
        "role": "system",
        "content": "testcode=11299"
    }
]

print("=" * 60)
print("测试：在 user 消息后插入 system 消息")
print("使用 Kimi 官方 API (k2.5)")
print("=" * 60)
print("\n发送的消息序列：")
for i, msg in enumerate(messages):
    print(f"{i+1}. role={msg['role']}, content={msg['content'][:50]}")

print("\n" + "=" * 60)
print("调用 Kimi API...")
print("=" * 60)

# 调用 API
headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json"
}

payload = {
    "model": "kimi-k2.5",
    "messages": messages
}

try:
    response = requests.post(
        f"{api_base}/chat/completions",
        headers=headers,
        json=payload,
        timeout=60
    )

    print(f"\nHTTP 状态码: {response.status_code}")

    if response.status_code == 200:
        result = response.json()
        content = result["choices"][0]["message"]["content"]
        print("\n模型回复：")
        print("-" * 60)
        print(content)
        print("-" * 60)
    else:
        print(f"\n错误响应: {response.text}")

except Exception as e:
    print(f"\n请求失败: {e}")

print("\n" + "=" * 60)
print("测试完成")
print("=" * 60)
