import speech_recognition as sr
from gtts import gTTS
import pygame
import os
import tempfile
import threading


class VoiceInput:
    def __init__(self):
        try:
            self.recognizer = sr.Recognizer()
            self.microphone = sr.Microphone()
            self.available = True
        except Exception:
            self.available = False

    def listen(self):
        if not self.available:
            return input("You: ")

        with self.microphone as source:
            print("Ana: Listening...")
            self.recognizer.adjust_for_ambient_noise(source)
            audio = self.recognizer.listen(source)
        try:
            text = self.recognizer.recognize_google(audio)
            return text
        except sr.UnknownValueError:
            return input("You: ")
        except sr.RequestError:
            return input("You: ")

    def listen_enhanced(self):
        from core.ui import info

        if not self.available:
            return input("You: ")

        with self.microphone as source:
            info("Listening...")
            self.recognizer.adjust_for_ambient_noise(source)
            audio = self.recognizer.listen(source)
        try:
            text = self.recognizer.recognize_google(audio)
            return text
        except sr.UnknownValueError:
            info("Could not understand audio, using text input...")
            return input("You: ")
        except sr.RequestError:
            info("Speech recognition error, using text input...")
            return input("You: ")


class VoiceOutput:
    def __init__(self):
        try:
            pygame.mixer.init()
            self.available = True
        except Exception:
            self.available = False

    def speak(self, text):
        if self.available:
            thread = threading.Thread(target=self._speak_async, args=(text,))
            thread.daemon = True
            thread.start()
        else:
            print(f"Ana: {text}")

    def _speak_async(self, text):
        try:
            with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as f:
                temp_file = f.name
            tts = gTTS(text=text, lang="en", slow=False)
            tts.save(temp_file)
            pygame.mixer.music.load(temp_file)
            pygame.mixer.music.play()
            while pygame.mixer.music.get_busy():
                pygame.time.Clock().tick(10)
            os.unlink(temp_file)
        except Exception:
            pass
