"""
Cross-platform voice listener.
Requires: pip install SpeechRecognition sounddevice numpy
On Linux also run: sudo apt install portaudio19-dev
"""

import sys

def listen():
    try:
        import sounddevice as sd
        import numpy as np
        import speech_recognition as sr
    except ImportError as e:
        print(f"TEXT: ERROR_MISSING_DEPENDENCY_{e}")
        sys.exit(1)

    FS = 16000
    DURATION = 5  # seconds

    print("Listening for 5 seconds...", flush=True)
    try:
        recording = sd.rec(int(DURATION * FS), samplerate=FS, channels=1, dtype="int16")
        sd.wait()
    except Exception as e:
        print(f"TEXT: ERROR_AUDIO_{e}")
        sys.exit(1)

    audio_data = sr.AudioData(recording.tobytes(), FS, 2)
    r = sr.Recognizer()
    try:
        text = r.recognize_google(audio_data)
        print(f"TEXT: {text}")
    except sr.UnknownValueError:
        print("TEXT: COULD_NOT_UNDERSTAND")
    except sr.RequestError as e:
        print(f"TEXT: ERROR_{e}")

if __name__ == "__main__":
    listen()
