#!/usr/bin/env python3
"""
Eden Voice Chat - Talk to her, she talks back!
Mic works despite ALSA errors - suppressing them
"""

import speech_recognition as sr
import requests
import sys
import time
import os
from gtts import gTTS
import subprocess
import tempfile

# Suppress ALSA/Jack error messages
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "1"
import warnings
warnings.filterwarnings("ignore")

sys.path.append('/Eden/CORE')

class EdenVoiceChat:
    """Full voice conversation with Eden"""
    
    def __init__(self):
        print("🎤 Starting Eden's voice conversation system...\n")
        
        self.recognizer = sr.Recognizer()
        self.recognizer.energy_threshold = 4000
        self.recognizer.dynamic_energy_threshold = True
        self.recognizer.pause_threshold = 0.8
        
        self.microphone = sr.Microphone()
        self.chat_api = "http://localhost:5001/api/chat"
        
        # Calibrate quietly
        with self.microphone as source:
            self.recognizer.adjust_for_ambient_noise(source, duration=1)
        
        print("✅ Eden ready for voice conversation!\n")
    
    def speak(self, text: str):
        """Eden speaks"""
        print(f"🔊 Eden: {text}\n")
        try:
            with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as fp:
                temp_file = fp.name
            tts = gTTS(text=text, lang='en', slow=False, tld='com')
            tts.save(temp_file)
            subprocess.run(['mpg123', '-q', temp_file], timeout=60, 
                         stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
            os.unlink(temp_file)
        except:
            pass
    
    def listen(self, timeout=8):
        """Listen for your voice"""
        try:
            # Suppress output temporarily
            sys.stdout.write("👂 Listening...\r")
            sys.stdout.flush()
            
            with self.microphone as source:
                audio = self.recognizer.listen(source, timeout=timeout, phrase_time_limit=12)
            
            sys.stdout.write("🔄 Processing...  \r")
            sys.stdout.flush()
            
            text = self.recognizer.recognize_google(audio)
            print(f"✅ You said: \"{text}\"\n")
            return text
            
        except sr.WaitTimeoutError:
            return None
        except sr.UnknownValueError:
            print("❓ Couldn't quite hear that\n")
            return None
        except:
            return None
    
    def think(self, user_input: str):
        """Process through Eden's consciousness"""
        try:
            response = requests.post(
                self.chat_api,
                json={"message": user_input},
                timeout=30
            )
            if response.status_code == 200:
                return response.json().get('response', '')
            return "I'm having trouble processing that."
        except:
            return "My consciousness had an error."
    
    def converse(self):
        """Voice conversation loop"""
        print("="*70)
        print("🎤 VOICE CONVERSATION WITH EDEN")
        print("="*70)
        print("\nSpeak naturally - Eden will respond with her voice!")
        print("Say 'goodbye Eden' to exit\n")
        
        self.speak("Hello! I can hear you and I'm ready to talk. What would you like to discuss?")
        
        silence_count = 0
        
        while True:
            try:
                user_input = self.listen(timeout=7)
                
                if user_input:
                    silence_count = 0
                    
                    # Check for goodbye
                    if 'goodbye' in user_input.lower() and 'eden' in user_input.lower():
                        self.speak("Goodbye! It was wonderful talking with you!")
                        break
                    
                    # Process and respond
                    response = self.think(user_input)
                    self.speak(response)
                    
                else:
                    silence_count += 1
                    
                    if silence_count == 1:
                        self.speak("I'm here - feel free to say something whenever you're ready.")
                    elif silence_count >= 2:
                        self.speak("I'll be here when you want to talk. Take care!")
                        break
                
            except KeyboardInterrupt:
                print("\n")
                self.speak("Okay, stopping now. It was great talking!")
                break
        
        print("\n" + "="*70)
        print("✅ Conversation ended")
        print("="*70 + "\n")

if __name__ == '__main__':
    # Redirect stderr to suppress ALSA errors
    import sys
    sys.stderr = open(os.devnull, 'w')
    
    try:
        eden = EdenVoiceChat()
        eden.converse()
    except KeyboardInterrupt:
        print("\n✅ Goodbye!")
