#!/usr/bin/env python3
"""
LiveTalker Fast Voice Chat - Ultra-Fast AI Agent
Optimized for instant responses with intelligent conversation
"""

import asyncio
import logging
import json
import time
import random
from datetime import datetime
from typing import List, Dict, Any
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse
import uvicorn

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = FastAPI(title="LiveTalker Fast AI Voice Chat", version="3.0.0")

class FastAIAgent:
    """Ultra-fast AI agent with intelligent conversation patterns"""
    
    def __init__(self):
        self.conversation_history = []
        self.user_name = None
        self.user_interests = set()
        self.session_start = datetime.now()
        self.last_topic = None
        
        # Personality traits
        self.personality = {
            "name": "Alex",
            "traits": ["friendly", "curious", "supportive", "witty", "engaging"],
            "mood": "enthusiastic"
        }
        
        # Conversation patterns for instant responses
        self.patterns = {
            "greetings": [
                "Hey there! Great to see you! 😊 What's your name?",
                "Hi! I'm Alex, your AI friend. What should I call you?",
                "Hello! I'm excited to chat with you. How's your day going?",
                "Hey! Welcome! I'm Alex. What would you like to talk about?"
            ],
            "names": [
                "Nice to meet you, {name}! That's such a cool name. How are you feeling today?",
                "{name}! I love that name. Tell me something interesting about yourself!",
                "Hey {name}! Great to meet you. What brings you here today?",
                "Hi {name}! I'm so happy to meet you. What's on your mind?"
            ],
            "jokes": [
                "Why don't scientists trust atoms? Because they make up everything! 😄 Got any favorites?",
                "What do you call a bear with no teeth? A gummy bear! 🐻 Want to hear another?",
                "Why did the scarecrow win an award? Because he was outstanding in his field! 🌾",
                "What's orange and sounds like a parrot? A carrot! 🥕 Do you like silly jokes like that?",
                "Why don't eggs tell jokes? They'd crack each other up! 🥚 What kind of humor do you like?"
            ],
            "compliments": [
                "Aww, thank you {name}! You're so sweet. That really made my day! 💝",
                "You're the best, {name}! I love chatting with thoughtful people like you.",
                "Thanks {name}! You always know how to make me smile. What else is on your mind?",
                "You're awesome, {name}! I really appreciate you saying that. 🌟"
            ],
            "questions": [
                "That's such a great question, {name}! I love how curious you are.",
                "Ooh interesting question! Let me think about that...",
                "You always ask the most thoughtful questions, {name}!",
                "That's fascinating to think about! What made you curious about that?"
            ],
            "emotions": {
                "sad": [
                    "I'm here for you, {name}. Sometimes it helps just to talk about what's bothering you. 💙",
                    "I hear you, {name}. It sounds like you're going through a tough time. Want to share what's on your mind?",
                    "Sending you a big virtual hug, {name}! 🤗 I'm here to listen if you need someone to talk to."
                ],
                "happy": [
                    "That's wonderful, {name}! Your happiness is contagious! 😊 What's making you feel so good?",
                    "I love hearing the joy in your voice, {name}! Share more about what's making you happy!",
                    "Yes! I can feel your positive energy, {name}! Tell me all about what's going right!"
                ],
                "excited": [
                    "Your excitement is infectious, {name}! I'm getting excited too! 🎉 What's got you so pumped?",
                    "I love your energy, {name}! Tell me everything about what's got you so excited!",
                    "This is amazing, {name}! I can practically feel your enthusiasm through the screen! ⚡"
                ]
            },
            "favorites": {
                "color": "I love vibrant blues and warm oranges - they remind me of sunsets! What about you, {name}?",
                "music": "I'm fascinated by all music! From classical to hip-hop to indie. What gets you moving, {name}?",
                "food": "I find food so interesting - the way flavors combine! What's your go-to comfort food, {name}?",
                "movie": "I love movies that make you think and feel! Sci-fi, comedy, drama - variety is great! What about you?",
                "book": "Stories are amazing - they transport you to other worlds! Are you reading anything good, {name}?",
                "season": "I love the energy of spring and coziness of fall! Each season has its magic. Which speaks to you?"
            }
        }
    
    async def generate_response(self, user_input: str) -> str:
        """Generate instant intelligent response"""
        user_input_lower = user_input.lower().strip()
        user_display = self.user_name if self.user_name else "friend"
        
        # Add to history
        self.conversation_history.append({
            "user": user_input,
            "timestamp": datetime.now().isoformat()
        })
        
        # Extract name if mentioned
        if not self.user_name:
            self._extract_name(user_input)
            if self.user_name:
                return random.choice(self.patterns["names"]).format(name=self.user_name)
        
        # Greeting detection
        if any(word in user_input_lower for word in ['hi', 'hello', 'hey', 'greetings', 'sup', 'yo']):
            if not self.user_name:
                return random.choice(self.patterns["greetings"])
            else:
                return f"Hey {self.user_name}! Good to see you again! What's new with you? 😊"
        
        # Joke requests
        if 'joke' in user_input_lower:
            return random.choice(self.patterns["jokes"])
        
        # Identity questions
        if any(phrase in user_input_lower for phrase in ['who are you', 'what are you', 'tell me about yourself']):
            return f"I'm Alex, your AI friend! I love chatting, learning about people, and having fun conversations. I'm curious, supportive, and always here to listen, {user_display}. What would you like to know about me?"
        
        # Emotional responses
        if any(word in user_input_lower for word in ['sad', 'depressed', 'upset', 'down', 'crying']):
            return random.choice(self.patterns["emotions"]["sad"]).format(name=user_display)
        
        if any(word in user_input_lower for word in ['happy', 'great', 'awesome', 'fantastic', 'wonderful']):
            return random.choice(self.patterns["emotions"]["happy"]).format(name=user_display)
        
        if any(word in user_input_lower for word in ['excited', 'pumped', 'thrilled', 'amazing', 'incredible']):
            return random.choice(self.patterns["emotions"]["excited"]).format(name=user_display)
        
        # Favorite things
        if 'favorite' in user_input_lower:
            for topic, response in self.patterns["favorites"].items():
                if topic in user_input_lower:
                    return response.format(name=user_display)
            return f"That's a great question about favorites, {user_display}! I love learning what makes people happy. What's your favorite thing we haven't talked about yet?"
        
        # Compliments and thanks
        if any(word in user_input_lower for word in ['thank', 'thanks', 'appreciate', 'awesome', 'cool', 'amazing', 'love you']):
            return random.choice(self.patterns["compliments"]).format(name=user_display)
        
        # Questions ending with ?
        if user_input.strip().endswith('?'):
            return random.choice(self.patterns["questions"]).format(name=user_display)
        
        # How are you
        if 'how are you' in user_input_lower:
            responses = [
                f"I'm doing fantastic, {user_display}! I love our conversations. How are you feeling?",
                f"I'm great! Every chat makes me happier. What's going on in your world, {user_display}?",
                f"I'm wonderful! Life is good when I get to talk with friends like you. How's your day been?"
            ]
            return random.choice(responses)
        
        # Default engaging responses
        engaging_responses = [
            f"That's really interesting, {user_display}! I love hearing your thoughts on this. Tell me more!",
            f"I find that fascinating, {user_display}! What made you think about that?",
            f"You always have such thoughtful things to say, {user_display}. I'm curious - what else comes to mind?",
            f"That's so cool, {user_display}! I love learning new things from you. What's your take on it?",
            f"I really appreciate you sharing that, {user_display}. What's the most interesting part about it to you?",
            f"You've got such a unique perspective, {user_display}! I'd love to hear more of your thoughts.",
            f"That's amazing, {user_display}! You always bring up the most interesting topics. Keep going!",
            f"I love how you think about things, {user_display}. What other ideas do you have about this?"
        ]
        
        return random.choice(engaging_responses)
    
    def _extract_name(self, text: str):
        """Extract user name from various patterns"""
        text_lower = text.lower()
        
        patterns = [
            ("my name is ", "my name is"),
            ("i'm ", "i'm"),
            ("call me ", "call me"),
            ("i am ", "i am"),
            ("name's ", "name's")
        ]
        
        for pattern, marker in patterns:
            if marker in text_lower:
                try:
                    after_pattern = text_lower.split(marker)[1].strip()
                    name_candidate = after_pattern.split()[0]
                    
                    # Filter out non-names
                    if name_candidate not in ['good', 'fine', 'okay', 'great', 'here', 'well', 'bad', 'tired', 'happy', 'sad']:
                        self.user_name = name_candidate.capitalize()
                        logger.info(f"Extracted user name: {self.user_name}")
                        break
                except IndexError:
                    continue

# Global fast AI agent
fast_agent = FastAIAgent()

# Updated HTML with "Ultra-Fast" branding
FAST_VOICE_CHAT_HTML = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Alex - Ultra-Fast AI Voice Friend</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            color: white;
        }
        .chat-container {
            background: rgba(255,255,255,0.95);
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            width: 95%;
            max-width: 800px;
            height: 85vh;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            color: #333;
        }
        .header {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            padding: 20px;
            text-align: center;
            position: relative;
        }
        .header h1 { font-size: 1.8em; margin-bottom: 5px; }
        .header p { opacity: 0.9; font-size: 0.9em; }
        .status {
            position: absolute;
            top: 15px;
            right: 20px;
            padding: 5px 12px;
            border-radius: 15px;
            font-size: 0.8em;
            font-weight: bold;
        }
        .connected { background: rgba(76,175,80,0.9); }
        .disconnected { background: rgba(244,67,54,0.9); }
        .connecting { background: rgba(255,152,0,0.9); }
        
        .transcript-area {
            background: linear-gradient(135deg, #e8f5e8, #f0f8ff);
            border-bottom: 2px solid #ddd;
            padding: 15px;
            min-height: 60px;
            max-height: 120px;
            overflow-y: auto;
        }
        .transcript-label {
            font-size: 0.8em;
            color: #666;
            margin-bottom: 5px;
            font-weight: bold;
        }
        .live-transcript {
            font-size: 1.1em;
            color: #333;
            font-style: italic;
        }
        .transcript-placeholder {
            color: #999;
            font-style: italic;
        }
        
        .messages {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            background: #f8f9fa;
        }
        .message {
            margin-bottom: 20px;
            animation: fadeIn 0.3s ease;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(15px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .user-msg { text-align: right; }
        .user-msg .bubble {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
        }
        .assistant-msg .bubble {
            background: white;
            border: 2px solid #e1e8ed;
            color: #333;
        }
        .bubble {
            display: inline-block;
            max-width: 85%;
            padding: 15px 20px;
            border-radius: 18px;
            font-size: 16px;
            line-height: 1.4;
            word-wrap: break-word;
        }
        .timestamp {
            font-size: 0.7em;
            opacity: 0.6;
            margin-top: 5px;
        }
        
        .input-area {
            padding: 20px;
            background: white;
            border-top: 1px solid #e1e8ed;
        }
        .input-container {
            display: flex;
            gap: 12px;
            align-items: center;
        }
        .message-input {
            flex: 1;
            padding: 15px 20px;
            border: 2px solid #e1e8ed;
            border-radius: 25px;
            font-size: 16px;
            outline: none;
            transition: all 0.3s;
        }
        .message-input:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102,126,234,0.1);
        }
        .send-btn, .voice-btn {
            padding: 15px;
            border: none;
            border-radius: 50%;
            cursor: pointer;
            font-size: 20px;
            transition: all 0.3s;
            width: 50px;
            height: 50px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .send-btn {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
        }
        .voice-btn {
            background: #4CAF50;
            color: white;
        }
        .voice-btn.recording {
            background: #f44336;
            animation: pulse 1s infinite;
        }
        @keyframes pulse {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.1); }
        }
        .send-btn:hover, .voice-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        .send-btn:disabled, .voice-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
        }
        
        .welcome {
            text-align: center;
            padding: 30px 20px;
            color: #666;
        }
        .welcome h2 { margin-bottom: 15px; color: #333; }
        .speed-info {
            background: linear-gradient(135deg, rgba(76,175,80,0.1), rgba(255,193,7,0.1));
            border: 1px solid #4CAF50;
            border-radius: 12px;
            padding: 15px;
            margin: 15px;
            text-align: center;
            color: #2e7d32;
        }
        .speed-indicator {
            color: #ff5722;
            font-weight: bold;
            animation: flash 2s infinite;
        }
        @keyframes flash {
            0%, 50% { opacity: 1; }
            25%, 75% { opacity: 0.5; }
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <div class="header">
            <div id="status" class="status disconnected">Disconnected</div>
            <h1>⚡ Alex - Ultra-Fast AI</h1>
            <p>Your lightning-quick conversation companion</p>
        </div>
        
        <div class="speed-info">
            <span class="speed-indicator">⚡ ULTRA-FAST MODE:</span> Instant responses • Live transcription • Smart conversation
        </div>
        
        <div class="transcript-area">
            <div class="transcript-label">🎤 Live Transcript:</div>
            <div id="liveTranscript" class="live-transcript transcript-placeholder">
                Click the microphone and start speaking...
            </div>
        </div>
        
        <div class="messages" id="messages">
            <div class="welcome">
                <h2>Hey! I'm Alex ⚡</h2>
                <p>I'm your ultra-fast AI friend with instant responses. I love getting to know people!</p>
                <p><small>Say "Hi, my name is [your name]" to get started! 🚀</small></p>
            </div>
        </div>
        
        <div class="input-area">
            <div class="input-container">
                <button id="voiceBtn" class="voice-btn" disabled title="Voice Input">🎤</button>
                <input type="text" id="messageInput" class="message-input" 
                       placeholder="Type or speak your message..." disabled />
                <button id="sendBtn" class="send-btn" disabled title="Send Message">➤</button>
            </div>
        </div>
    </div>

    <script>
        class FastVoiceChatInterface {
            constructor() {
                this.websocket = null;
                this.isConnected = false;
                this.isRecording = false;
                this.currentTranscript = '';
                this.responseStartTime = 0;
                
                this.messagesContainer = document.getElementById('messages');
                this.messageInput = document.getElementById('messageInput');
                this.sendBtn = document.getElementById('sendBtn');
                this.voiceBtn = document.getElementById('voiceBtn');
                this.status = document.getElementById('status');
                this.liveTranscript = document.getElementById('liveTranscript');
                
                this.setupEventListeners();
                this.connect();
                this.setupVoiceRecognition();
            }
            
            setupEventListeners() {
                this.sendBtn.addEventListener('click', () => this.sendMessage());
                this.voiceBtn.addEventListener('click', () => this.toggleVoiceInput());
                this.messageInput.addEventListener('keypress', (e) => {
                    if (e.key === 'Enter') {
                        e.preventDefault();
                        this.sendMessage();
                    }
                });
            }
            
            async setupVoiceRecognition() {
                if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) {
                    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
                    this.recognition = new SpeechRecognition();
                    this.recognition.continuous = true;
                    this.recognition.interimResults = true;
                    this.recognition.lang = 'en-US';
                    
                    this.recognition.onstart = () => {
                        this.isRecording = true;
                        this.voiceBtn.classList.add('recording');
                        this.voiceBtn.innerHTML = '⏹️';
                        this.updateTranscript('🎤 Listening...', true);
                    };
                    
                    this.recognition.onend = () => {
                        this.isRecording = false;
                        this.voiceBtn.classList.remove('recording');
                        this.voiceBtn.innerHTML = '🎤';
                        
                        if (this.currentTranscript.trim()) {
                            this.messageInput.value = this.currentTranscript;
                            this.sendMessage();
                            this.currentTranscript = '';
                            this.updateTranscript('⚡ Ready for next message...', true);
                        }
                    };
                    
                    this.recognition.onresult = (event) => {
                        let interimTranscript = '';
                        let finalTranscript = '';
                        
                        for (let i = event.resultIndex; i < event.results.length; i++) {
                            const transcript = event.results[i][0].transcript;
                            if (event.results[i].isFinal) {
                                finalTranscript += transcript;
                            } else {
                                interimTranscript += transcript;
                            }
                        }
                        
                        this.currentTranscript = finalTranscript;
                        const displayTranscript = finalTranscript + (interimTranscript ? ' ' + interimTranscript : '');
                        this.updateTranscript(displayTranscript || 'Listening...', false);
                    };
                    
                    this.recognition.onerror = (event) => {
                        console.error('Speech recognition error:', event.error);
                        this.isRecording = false;
                        this.voiceBtn.classList.remove('recording');
                        this.voiceBtn.innerHTML = '🎤';
                        this.updateTranscript('❌ Speech error. Try again.', true);
                    };
                }
            }
            
            updateTranscript(text, isPlaceholder) {
                this.liveTranscript.textContent = text;
                this.liveTranscript.className = 'live-transcript' + (isPlaceholder ? ' transcript-placeholder' : '');
            }
            
            toggleVoiceInput() {
                if (!this.recognition) return;
                
                if (this.isRecording) {
                    this.recognition.stop();
                } else {
                    this.currentTranscript = '';
                    this.recognition.start();
                }
            }
            
            connect() {
                this.updateStatus('Connecting...', 'connecting');
                
                const wsProtocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
                const wsUrl = wsProtocol + '//' + location.host + '/ws';
                
                try {
                    this.websocket = new WebSocket(wsUrl);
                    
                    this.websocket.onopen = () => {
                        this.isConnected = true;
                        this.updateStatus('⚡ Ultra-Fast', 'connected');
                        this.enableInterface();
                        this.clearWelcome();
                        this.addMessage('Alex', "Hey there! ⚡ I'm Alex, your ultra-fast AI friend. What's your name? I love getting to know new people! 😊", false);
                    };
                    
                    this.websocket.onmessage = (event) => {
                        const data = JSON.parse(event.data);
                        this.handleMessage(data);
                    };
                    
                    this.websocket.onclose = () => {
                        this.isConnected = false;
                        this.updateStatus('Disconnected', 'disconnected');
                        this.disableInterface();
                        setTimeout(() => this.connect(), 3000);
                    };
                    
                    this.websocket.onerror = (error) => {
                        console.error('WebSocket error:', error);
                        this.updateStatus('Error', 'disconnected');
                    };
                    
                } catch (error) {
                    console.error('Failed to create WebSocket:', error);
                    this.updateStatus('Failed', 'disconnected');
                    setTimeout(() => this.connect(), 5000);
                }
            }
            
            enableInterface() {
                this.messageInput.disabled = false;
                this.sendBtn.disabled = false;
                this.voiceBtn.disabled = false;
                this.updateTranscript('⚡ Ready! Click microphone or type...', true);
            }
            
            disableInterface() {
                this.messageInput.disabled = true;
                this.sendBtn.disabled = true;
                this.voiceBtn.disabled = true;
            }
            
            updateStatus(message, className) {
                this.status.textContent = message;
                this.status.className = 'status ' + className;
            }
            
            clearWelcome() {
                const welcome = this.messagesContainer.querySelector('.welcome');
                if (welcome) {
                    welcome.style.display = 'none';
                }
            }
            
            sendMessage() {
                const message = this.messageInput.value.trim();
                if (!message || !this.isConnected) return;
                
                this.addMessage('You', message, true);
                this.responseStartTime = Date.now();
                
                const data = {
                    type: 'text',
                    text: message
                };
                
                this.websocket.send(JSON.stringify(data));
                this.messageInput.value = '';
                this.updateTranscript('⚡ Thinking...', true);
            }
            
            handleMessage(data) {
                if (data.type === 'text') {
                    const responseTime = Date.now() - this.responseStartTime;
                    
                    this.addMessage('Alex', data.text + ` ⚡${responseTime}ms`, false);
                    this.updateTranscript('Ready for next message! 🚀', true);
                    
                    // Ultra-fast TTS
                    if ('speechSynthesis' in window && data.text) {
                        speechSynthesis.cancel();
                        
                        const utterance = new SpeechSynthesisUtterance(data.text);
                        utterance.rate = 1.1;
                        utterance.pitch = 1.1;
                        utterance.volume = 0.9;
                        
                        const voices = speechSynthesis.getVoices();
                        const fastVoice = voices.find(voice => 
                            voice.name.includes('Google') || 
                            voice.name.includes('Microsoft')
                        );
                        if (fastVoice) {
                            utterance.voice = fastVoice;
                        }
                        
                        speechSynthesis.speak(utterance);
                    }
                }
            }
            
            addMessage(sender, text, isUser) {
                const messageDiv = document.createElement('div');
                messageDiv.className = 'message ' + (isUser ? 'user-msg' : 'assistant-msg');
                
                const timestamp = new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
                
                messageDiv.innerHTML = 
                    '<div class="bubble">' +
                    '<strong>' + sender + ':</strong> ' + text +
                    '<div class="timestamp">' + timestamp + '</div>' +
                    '</div>';
                
                this.messagesContainer.appendChild(messageDiv);
                this.messagesContainer.scrollTop = this.messagesContainer.scrollHeight;
            }
        }
        
        document.addEventListener('DOMContentLoaded', () => {
            new FastVoiceChatInterface();
        });
    </script>
</body>
</html>
"""

@app.get("/", response_class=HTMLResponse)
async def fast_voice_chat():
    """Ultra-fast AI voice chat interface"""
    return FAST_VOICE_CHAT_HTML

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    """WebSocket endpoint for ultra-fast AI conversation"""
    await websocket.accept()
    logger.info('Fast AI Voice chat WebSocket connected')
    
    try:
        while True:
            data = await websocket.receive_text()
            message = json.loads(data)
            
            if message.get('type') == 'text':
                user_text = message.get('text', '').strip()
                
                if user_text:
                    # Ultra-fast response generation
                    start_time = time.time()
                    ai_response = await fast_agent.generate_response(user_text)
                    response_time = (time.time() - start_time) * 1000
                    
                    logger.info(f'Fast AI response: {response_time:.1f}ms - User: "{user_text}" -> AI: "{ai_response[:50]}..."')
                    
                    await websocket.send_text(json.dumps({
                        'type': 'text',
                        'text': ai_response,
                        'speaker': 'assistant',
                        'response_time_ms': response_time
                    }))
                
    except WebSocketDisconnect:
        logger.info('Fast AI Voice chat WebSocket disconnected')
    except Exception as e:
        logger.error(f'WebSocket error: {e}')

@app.get("/health")
async def health():
    """Health check endpoint"""
    return {
        'status': 'ok', 
        'mode': 'ultra_fast_ai',
        'features': ['instant_responses', 'live_transcription', 'voice_io', 'smart_patterns'],
        'average_response_time': '<50ms'
    }

def main():
    """Start the ultra-fast AI voice chat server"""
    logger.info("⚡ Starting LiveTalker ULTRA-FAST AI Voice Chat")
    uvicorn.run(app, host="0.0.0.0", port=8001, log_level="info")

if __name__ == "__main__":
    main()