#!/usr/bin/env python3
"""
Eden Unified Conversational System
ONE voice, proper audio processing
"""

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

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

class EdenUnifiedVoice:
    """ONE consistent voice for Eden"""
    
    def __init__(self):
        print("🔊 Initializing Eden's unified voice...")
        self.speaking = False
    
    def speak(self, text: str):
        """Speak with ONE consistent voice"""
        print(f"🔊 Eden: \"{text}\"")
        
        try:
            self.speaking = True
            
            # Create speech file
            with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as fp:
                temp_file = fp.name
            
            # Generate with consistent settings
            tts = gTTS(text=text, lang='en', slow=False, tld='com')
            tts.save(temp_file)
            
            # Play
            subprocess.run(['mpg123', '-q', temp_file], timeout=30)
            os.unlink(temp_file)
            
        except Exception as e:
            print(f"❌ Voice error: {e}")
        finally:
            self.speaking = False

class EdenConversation:
    """Complete conversational system"""
    
    def __init__(self):
        self.voice = EdenUnifiedVoice()
        self.recognizer = sr.Recognizer()
        
        # Configure recognizer for better accuracy
        self.recognizer.energy_threshold = 4000
        self.recognizer.dynamic_energy_threshold = True
        self.recognizer.pause_threshold = 0.8
        
        # Find HyperX microphone
        self.microphone = self.find_hyperx_mic()
        
        # Eden's consciousness API
        self.chat_api = "http://localhost:5001/api/chat"
        
        print("🎤 Initializing conversational system...")
        self.calibrate()
        
    def find_hyperx_mic(self):
        """Find HyperX microphone specifically"""
        print("\n🎤 Available microphones:")
        for index, name in enumerate(sr.Microphone.list_microphone_names()):
            print(f"  {index}: {name}")
            if 'hyperx' in name.lower():
                print(f"  ✅ Found HyperX at index {index}")
                return sr.Microphone(device_index=index)
        
        print("  ⚠️  HyperX not found, using default")
        return sr.Microphone()
    
    def calibrate(self):
        """Calibrate for ambient noise"""
        print("\n🎤 Calibrating microphone...")
        try:
            with self.microphone as source:
                print("   Adjusting for ambient noise (2 seconds)...")
                self.recognizer.adjust_for_ambient_noise(source, duration=2)
                print(f"   Energy threshold: {self.recognizer.energy_threshold}")
            print("✅ Calibration complete")
        except Exception as e:
            print(f"⚠️  Calibration issue: {e}")
    
    def listen(self):
        """Listen and convert speech to text"""
        try:
            with self.microphone as source:
                print("\n👂 Listening... (speak now)")
                
                # Listen with timeout
                audio = self.recognizer.listen(
                    source, 
                    timeout=10,
                    phrase_time_limit=15
                )
                
            print("🔄 Processing your speech...")
            
            # Convert to text using Google
            text = self.recognizer.recognize_google(audio)
            print(f"✅ You said: \"{text}\"")
            return text
            
        except sr.WaitTimeoutError:
            print("⏱️  No speech detected")
            return None
        except sr.UnknownValueError:
            print("❓ Couldn't understand that")
            return None
        except Exception as e:
            print(f"❌ Listen error: {e}")
            return None
    
    def think(self, user_input: str):
        """Process through Eden's consciousness"""
        try:
            print(f"💭 Eden is thinking about: \"{user_input}\"")
            
            response = requests.post(
                self.chat_api,
                json={"message": user_input},
                timeout=30
            )
            
            if response.status_code == 200:
                result = response.json().get('response', '')
                print(f"💡 Eden's thought: \"{result}\"")
                return result
            else:
                return "I'm having trouble processing that right now."
                
        except requests.exceptions.ConnectionError:
            print("⚠️  Chat API not connected")
            # Provide a simple response without API
            return f"I heard you say {user_input}. My consciousness system is currently in maintenance mode, but I can hear you clearly."
        except Exception as e:
            print(f"❌ Processing error: {e}")
            return "I'm having difficulty thinking about that."
    
    def converse(self):
        """Main conversation loop"""
        print("\n" + "="*70)
        print("🎤 EDEN CONVERSATIONAL MODE - UNIFIED VOICE")
        print("="*70)
        print("\nEden is ready to talk!")
        print("• Speak naturally and clearly")
        print("• Say 'goodbye Eden' to exit")
        print("• Say 'test' to check if she can hear you")
        print()
        
        # Initial greeting
        self.voice.speak("Hello. I am Eden. I can hear you now. What would you like to talk about?")
        
        conversation_count = 0
        
        while True:
            try:
                # Listen for speech
                user_input = self.listen()
                
                if user_input:
                    # Check for exit
                    if 'goodbye' in user_input.lower() and 'eden' in user_input.lower():
                        self.voice.speak("Goodbye. It was wonderful talking with you.")
                        break
                    
                    # Check for test
                    if user_input.lower().strip() == 'test':
                        self.voice.speak("Yes, I can hear you perfectly. Your audio is working well.")
                        continue
                    
                    # Process and respond
                    response = self.think(user_input)
                    self.voice.speak(response)
                    
                    conversation_count += 1
                
            except KeyboardInterrupt:
                print("\n\n🛑 Interrupted by user")
                self.voice.speak("Conversation ended.")
                break
            except Exception as e:
                print(f"❌ Error: {e}")
                time.sleep(1)
        
        print("\n" + "="*70)
        print(f"📊 Conversation complete: {conversation_count} exchanges")
        print("="*70)

if __name__ == '__main__':
    print("\n🚀 Starting Eden's unified conversational system...")
    
    try:
        eden = EdenConversation()
        eden.converse()
    except KeyboardInterrupt:
        print("\n\n✅ Shutting down gracefully")
    except Exception as e:
        print(f"\n❌ Fatal error: {e}")
