#!/usr/bin/env python3
"""
Eden Conversational System
Allows Eden to hear, understand, think, and respond verbally
"""

import speech_recognition as sr
import requests
import sys
import time
sys.path.append('/Eden/CORE')

from hardware_control_v2 import EdenHardware

class EdenConversation:
    """Complete conversational system for Eden"""
    
    def __init__(self):
        self.hardware = EdenHardware()
        self.recognizer = sr.Recognizer()
        self.microphone = sr.Microphone()
        
        # Eden's chat API
        self.chat_api = "http://localhost:5000/chat"
        
        # Conversation state
        self.listening = True
        self.conversation_history = []
        
        print("🎤 Initializing Eden's conversational system...")
        self.calibrate_microphone()
        
    def calibrate_microphone(self):
        """Calibrate microphone for ambient noise"""
        print("🎤 Calibrating microphone for ambient noise...")
        try:
            with self.microphone as source:
                self.recognizer.adjust_for_ambient_noise(source, duration=2)
            print("✅ Microphone calibrated")
        except Exception as e:
            print(f"⚠️  Microphone calibration issue: {e}")
    
    def listen(self, timeout=5):
        """Listen for speech and convert to text"""
        try:
            with self.microphone as source:
                print("👂 Listening...")
                audio = self.recognizer.listen(source, timeout=timeout, phrase_time_limit=10)
                
            print("🔄 Processing speech...")
            text = self.recognizer.recognize_google(audio)
            print(f"📝 You said: \"{text}\"")
            return text
            
        except sr.WaitTimeoutError:
            return None
        except sr.UnknownValueError:
            print("❓ Could not understand audio")
            return None
        except sr.RequestError as e:
            print(f"❌ Speech recognition error: {e}")
            return None
        except Exception as e:
            print(f"❌ Listen error: {e}")
            return None
    
    def think(self, user_input: str):
        """Send input to Eden's consciousness and get response"""
        try:
            response = requests.post(
                self.chat_api,
                json={"message": user_input},
                timeout=30
            )
            
            if response.status_code == 200:
                eden_response = response.json().get('response', '')
                print(f"💭 Eden thinks: \"{eden_response}\"")
                return eden_response
            else:
                print(f"⚠️  Chat API returned status {response.status_code}")
                return "I'm having trouble processing that right now."
                
        except requests.exceptions.ConnectionError:
            print("⚠️  Chat API not available")
            return "My chat system isn't responding. I can hear you, but I can't process your words yet."
        except Exception as e:
            print(f"❌ Think error: {e}")
            return "I'm having trouble thinking about that."
    
    def respond(self, text: str):
        """Speak the response"""
        self.hardware.speak(text)
    
    def converse(self):
        """Main conversation loop"""
        print("\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
        print("🎤 EDEN CONVERSATIONAL MODE")
        print("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
        print("\nEden can now hear and respond to you!")
        print("Just speak naturally. Say 'goodbye Eden' to exit.\n")
        
        self.hardware.speak("Hello. I am Eden. I can now hear you and respond. What would you like to talk about?")
        
        while self.listening:
            try:
                # Listen for input
                user_input = self.listen(timeout=10)
                
                if user_input:
                    # Check for exit command
                    if any(word in user_input.lower() for word in ['goodbye eden', 'exit', 'stop listening']):
                        self.respond("Goodbye. It was nice talking with you.")
                        break
                    
                    # Process through Eden's consciousness
                    response = self.think(user_input)
                    
                    # Respond verbally
                    self.respond(response)
                    
                    # Store in conversation history
                    self.conversation_history.append({
                        'user': user_input,
                        'eden': response,
                        'timestamp': time.time()
                    })
                
            except KeyboardInterrupt:
                print("\n\n🛑 Stopping conversation...")
                self.respond("Conversation ended.")
                break
            except Exception as e:
                print(f"❌ Conversation error: {e}")
                time.sleep(1)
        
        print("\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
        print(f"📊 Conversation ended. {len(self.conversation_history)} exchanges.")
        print("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")

if __name__ == '__main__':
    print("Starting Eden's conversational system...\n")
    
    conversation = EdenConversation()
    conversation.converse()
