#!/usr/bin/env python3
"""Quick test: does the G1 built-in speaker work via AudioClient?"""

import sys
import time
import json
from unitree_sdk2py.core.channel import ChannelFactoryInitialize
from unitree_sdk2py.g1.audio.g1_audio_client import AudioClient
from unitree_sdk2py.g1.audio.g1_audio_api import *

if len(sys.argv) < 2:
    print(f"Usage: python3 {sys.argv[0]} <network_interface>")
    print(f"  e.g. python3 {sys.argv[0]} enp3s0")
    sys.exit(1)

iface = sys.argv[1]
print(f"Connecting via {iface}...")
ChannelFactoryInitialize(0, iface)

client = AudioClient()
client.SetTimeout(10.0)
client.Init()

# Test 1: Volume
print("\n--- Test 1: GetVolume ---")
code, vol = client.GetVolume()
print(f"  code={code}, volume={vol}")

print("\n--- Test 2: SetVolume(100) ---")
code = client.SetVolume(100)
print(f"  code={code}")

# Test 3: LED (visual confirmation that RPC works)
print("\n--- Test 3: LED Red ---")
code = client.LedControl(255, 0, 0)
print(f"  code={code}")
time.sleep(1)

print("--- Test 3b: LED Green ---")
code = client.LedControl(0, 255, 0)
print(f"  code={code}")
time.sleep(1)

print("--- Test 3c: LED off ---")
code = client.LedControl(0, 0, 0)
print(f"  code={code}")

# Test 4: TTS
print("\n--- Test 4: TTS 'Hello, testing speaker' ---")
code = client.TtsMaker("Hello, testing speaker", 0)
print(f"  code={code}")
time.sleep(3)

print("\n--- Test 5: TTS Chinese ---")
code = client.TtsMaker("你好，测试声音", 0)
print(f"  code={code}")
time.sleep(3)

# Test 6: Try _Call with AUDIO_START_PLAY different formats
print("\n--- Test 6: _Call AUDIO_START_PLAY formats ---")
import wave
import numpy as np
from pathlib import Path

wav_path = Path(__file__).parent / "DataG1" / "greeting.wav"
if wav_path.exists():
    with wave.open(str(wav_path), "rb") as wf:
        pcm = wf.readframes(wf.getnframes())
    # Small chunk for testing
    chunk = pcm[:4096]

    # Format A: just JSON with pcm as list of ints
    param_a = json.dumps({"pcm": list(chunk[:256])})
    code_a, data_a = client._Call(ROBOT_API_ID_AUDIO_START_PLAY, param_a)
    print(f"  Format A (_Call, pcm list):  code={code_a}")

    # Format B: _CallBinary with raw bytes
    code_b, data_b = client._CallBinary(ROBOT_API_ID_AUDIO_START_PLAY, list(chunk[:256]))
    print(f"  Format B (_CallBinary, raw): code={code_b}")

    # Format C: _Call with app_name
    param_c = json.dumps({"app_name": "test", "stream_id": "s1"})
    code_c, data_c = client._Call(ROBOT_API_ID_AUDIO_START_PLAY, param_c)
    print(f"  Format C (_Call, app_name):  code={code_c}")
else:
    print(f"  No greeting.wav found, skipping PCM tests")

print("\nDone. Did you hear anything or see LED changes?")
