#!/usr/bin/env python3
"""
generate_test_audio.py
======================
Generates WAV audio files for browser agent voice widget testing.
These WAV files are injected as a fake microphone via Chrome flags:
  --use-fake-ui-for-media-stream
  --use-fake-device-for-media-stream
  --use-file-for-fake-audio-capture=/path/to/question.wav

Usage:
  python3 scripts/generate_test_audio.py

Output:
  /tmp/tw_test_audio/q1_first_visit.wav      -- New visitor question
  /tmp/tw_test_audio/q2_return_visit.wav     -- Returning visitor check
  /tmp/tw_test_audio/q3_pricing.wav          -- Pricing enquiry
  /tmp/tw_test_audio/q4_booking.wav          -- Booking request

Dependencies:
  pip3 install gtts pydub
  (pydub needs ffmpeg: sudo apt-get install ffmpeg)

Fallback:
  If gtts unavailable, generates a pure sine-wave WAV (silent test).
"""

import os
import sys
import struct
import math
import wave

OUTPUT_DIR = "/tmp/tw_test_audio"

QUESTIONS = {
    "q1_first_visit": "Hi, I found your website. Can you tell me what Talking Widget does?",
    "q2_return_visit": "Hey, I called before. I wanted to follow up on adding a voice widget to my site.",
    "q3_pricing": "What are your pricing plans? How much does it cost per month?",
    "q4_booking": "I'd like to book a demo. Are you available this week?",
    "q5_memory_test": "Do you remember what we talked about last time I called?",
}


def generate_wav_gtts(text: str, output_path: str) -> bool:
    """Generate WAV from text using Google TTS (internet required)."""
    try:
        from gtts import gTTS
        import io
        from pydub import AudioSegment

        tts = gTTS(text=text, lang="en", slow=False)
        mp3_buffer = io.BytesIO()
        tts.write_to_fp(mp3_buffer)
        mp3_buffer.seek(0)

        audio = AudioSegment.from_mp3(mp3_buffer)
        # Chrome fake audio capture requires: mono, 16-bit, 16000Hz or 44100Hz
        audio = audio.set_channels(1).set_frame_rate(16000).set_sample_width(2)
        audio.export(output_path, format="wav")
        return True
    except Exception as e:
        print(f"  [gtts] Failed: {e}")
        return False


def generate_wav_sine(text: str, output_path: str, duration_seconds: float = 3.0) -> bool:
    """
    Fallback: generate a sine wave WAV file.
    Chrome will inject this as the fake mic input.
    The AI won't transcribe meaningful speech, but connection/infrastructure tests pass.
    """
    sample_rate = 16000
    frequency = 440  # A4 note
    num_samples = int(sample_rate * duration_seconds)
    amplitude = 16000

    with wave.open(output_path, "w") as wav_file:
        wav_file.setnchannels(1)       # Mono
        wav_file.setsampwidth(2)       # 16-bit
        wav_file.setframerate(sample_rate)

        frames = []
        for i in range(num_samples):
            sample = int(amplitude * math.sin(2 * math.pi * frequency * i / sample_rate))
            frames.append(struct.pack("<h", sample))

        wav_file.writeframes(b"".join(frames))

    return True


def main():
    os.makedirs(OUTPUT_DIR, exist_ok=True)

    # Try gtts first, fall back to sine wave
    try:
        from gtts import gTTS
        from pydub import AudioSegment
        use_gtts = True
        print("[audio] Using Google TTS for realistic speech audio")
    except ImportError:
        use_gtts = False
        print("[audio] gtts/pydub not available — generating sine wave audio (silent test)")
        print("        Install with: pip3 install gtts pydub && sudo apt-get install ffmpeg")

    for name, text in QUESTIONS.items():
        output_path = os.path.join(OUTPUT_DIR, f"{name}.wav")
        print(f"  Generating: {name}.wav")
        print(f"    Text: \"{text}\"")

        if use_gtts:
            ok = generate_wav_gtts(text, output_path)
            if not ok:
                generate_wav_sine(text, output_path)
        else:
            generate_wav_sine(text, output_path)

        if os.path.exists(output_path):
            size = os.path.getsize(output_path)
            print(f"    ✅ Created: {output_path} ({size:,} bytes)")
        else:
            print(f"    ❌ Failed to create: {output_path}")

    print(f"\n✅ Audio files ready in: {OUTPUT_DIR}")
    print("\nUse with Playwright:")
    print(f"  --use-fake-ui-for-media-stream")
    print(f"  --use-fake-device-for-media-stream")
    print(f"  --use-file-for-fake-audio-capture={OUTPUT_DIR}/q1_first_visit.wav")


if __name__ == "__main__":
    main()
