import urllib.request
import urllib.error
import json
import time

def test_abnormal_trigger():
    url = "http://172.20.10.2:8000/abnormal_trigger"
    
    payload = {
        "type": "abnormal_trigger",
        "trigger_reason": "poor_skin",
        "enable_streaming": True, # The server handles it by accumulating, but we keep the field
        "context_data": {
            "emotion": "sad",
            "skin_status": {
                "acne": True,
                "dark_circles": True
            },
            "timestamp": "2024-01-01 12:30:45"
        }
    }
    
    data = json.dumps(payload).encode('utf-8')
    req = urllib.request.Request(url, data=data, headers={'Content-Type': 'application/json'})
    
    print(f"Sending request to {url}...")
    start_time = time.time()
    
    try:
        with urllib.request.urlopen(req) as response:
            if response.status == 200:
                print("Request successful!")
                output_file = "response.pcm"
                
                # Read content
                audio_data = response.read()
                
                with open(output_file, "wb") as f:
                    f.write(audio_data)
                    
                elapsed = time.time() - start_time
                print(f"Audio saved to {output_file} ({len(audio_data)} bytes)")
                print(f"Time taken: {elapsed:.2f} seconds")
                
                # Optional: detailed check
                if len(audio_data) < 100:
                    print("Warning: Audio file seems too small.")
            else:
                print(f"Error: {response.status}")
                print(response.read().decode('utf-8'))
            
    except urllib.error.URLError as e:
        print(f"Error: {e}")
        if hasattr(e, 'read'):
             print(e.read().decode('utf-8'))

if __name__ == "__main__":
    test_abnormal_trigger()
