import urllib.request
import json
import time

# First test fast_langdetect lite model works
print("Testing fast_langdetect lite model...")
try:
    import fast_langdetect
    result = fast_langdetect.detect("你好世界", model="lite")
    print("fast_langdetect lite test passed:", result)
except Exception as e:
    print("fast_langdetect lite test failed:", e)
    import traceback
    traceback.print_exc()

# Test TTS API
print("\nTesting TTS API...")
data = json.dumps({
    "text": "你好，这是一个语音合成测试。",
    "text_lang": "zh",
    "ref_audio_path": "D:/AI-Ad-Agent/portal/data/default_ref.wav",
    "prompt_text": "",
    "prompt_lang": "zh",
    "text_split_method": "cut5",
    "media_type": "wav"
}).encode()

req = urllib.request.Request('http://127.0.0.1:9880/tts', data=data, headers={'Content-Type': 'application/json'})
start = time.time()
try:
    with urllib.request.urlopen(req, timeout=120) as resp:
        result = resp.read()
        elapsed = time.time() - start
        print(f'Success, received {len(result)} bytes in {elapsed:.1f}s')
        with open('D:/AI-Ad-Agent/portal/data/tts_test_result.wav', 'wb') as f:
            f.write(result)
        print('Saved to D:/AI-Ad-Agent/portal/data/tts_test_result.wav')
except Exception as e:
    elapsed = time.time() - start
    print(f'Error after {elapsed:.1f}s: {e}')
    import traceback
    traceback.print_exc()
