#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""CosyVoice 测试 - 排查问题"""

import requests, json, time, os

API_KEY = "sk-c25679401ba24c749f53be86b0c9a7a6"
API_URL = "https://dashscope.aliyuncs.com/api/v1/services/audio/tts/SpeechSynthesizer"
OUTPUT_DIR = "test-results"
os.makedirs(OUTPUT_DIR, exist_ok=True)

def test(text, model, voice, label):
    payload = {
        "model": model,
        "input": {"text": text, "voice": voice, "format": "mp3", "sample_rate": 24000}
    }
    headers = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}
    
    t0 = time.time()
    resp = requests.post(API_URL, headers=headers, json=payload, timeout=60)
    elapsed = time.time() - t0
    
    data = resp.json()
    status = "✅" if resp.status_code == 200 else "❌"
    code = data.get("code", "OK") if resp.status_code != 200 else "OK"
    msg = data.get("message", "") if resp.status_code != 200 else "success"
    
    print(f"{status} [{label}] HTTP {resp.status_code} | {code} | {msg[:80]} | {elapsed:.1f}s")
    
    if resp.status_code == 200:
        audio_url = data.get("output", {}).get("audio", {}).get("url", "")
        chars = data.get("usage", {}).get("characters", 0)
        print(f"    字符数: {chars}, 音频URL: {audio_url[:80]}...")
        
        # 下载
        ar = requests.get(audio_url, timeout=30)
        if ar.status_code == 200:
            fname = os.path.join(OUTPUT_DIR, f"test-{label}-{int(time.time())}.mp3")
            with open(fname, "wb") as f: f.write(ar.content)
            print(f"    已保存: {fname} ({len(ar.content)} bytes)")
    
    return resp.status_code == 200

print("=" * 50)
print("  CosyVoice 故障排查")
print("=" * 50)

# 尝试不同模型+音色组合
short_text = "你好，这是一段测试文本。欢迎使用CosyVoice语音合成服务。"

tests = [
    # model, voice, label
    ("cosyvoice-v3.5-flash", "longanyang", "v3.5-flash+longanyang"),
    ("cosyvoice-v3.5-plus", "longanyang", "v3.5-plus+longanyang"),
    ("cosyvoice-v3-flash", "longanyang", "v3-flash+longanyang"),
    ("cosyvoice-v3.5-flash", "longxiaoxia", "v3.5-flash+longxiaoxia"),
    ("cosyvoice-v1", "longanyang", "v1+longanyang"),
    ("cosyvoice-v3.5-flash", "longyu", "v3.5-flash+longyu"),
    ("cosyvoice-v3-flash", "longyu", "v3-flash+longyu"),
]

for model, voice, label in tests:
    if test(short_text, model, voice, label):
        print(f"  >>> 成功组合: model={model}, voice={voice}\n")
        break
