#!/usr/bin/env python3
"""
Zero Voice Webhook Handler - Handles Twilio callbacks and conversation flow
"""

import os
import json
import sqlite3
from datetime import datetime
from flask import Flask, request, Response
from flask_cors import CORS
from dotenv import load_dotenv
import random

# Load environment variables
load_dotenv()

app = Flask(__name__)
CORS(app)

# Configuration
DATABASE_URL = os.getenv('DATABASE_URL', 'sqlite:///app/data/zero_voice.db')
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')

# Extract SQLite path
if DATABASE_URL.startswith('sqlite://'):
    DB_PATH = DATABASE_URL.replace('sqlite://', '')
else:
    DB_PATH = '/app/data/zero_voice.db'

# Personality responses
PERSONALITIES = {
    'Alex': {
        'name': 'Alex',
        'voice': 'alice',
        'style': 'professional',
        'greetings': [
            'Hello! This is Alex from Zero Voice. How may I assist you today?',
            'Good day! Alex here. How can I help you?',
            'Thank you for calling. This is Alex. What can I do for you?'
        ],
        'responses': [
            'I understand your concern. Let me help you with that.',
            'That\'s a great question. Here\'s what I can do for you.',
            'I appreciate you bringing this to my attention. Let me assist you.'
        ],
        'closings': [
            'Thank you for your time. Have a wonderful day!',
            'It was my pleasure assisting you. Goodbye!',
            'Thank you for calling. Take care!'
        ]
    },
    'Jamie': {
        'name': 'Jamie',
        'voice': 'alloy',
        'style': 'friendly',
        'greetings': [
            'Hey there! Jamie from Zero Voice here! How\'s your day going?',
            'Hi! This is Jamie! So glad you called. What can I help you with?',
            'Hello! Jamie here, ready to help! What brings you here today?'
        ],
        'responses': [
            'Oh, that\'s interesting! Let me see what I can do!',
            'Absolutely! I\'d love to help you with that!',
            'That sounds important! Let\'s work on this together!'
        ],
        'closings': [
            'It was so great talking with you! Have an amazing day!',
            'Thanks for the chat! Take care and stay awesome!',
            'Bye for now! Hope to talk to you again soon!'
        ]
    },
    'Sam': {
        'name': 'Sam',
        'voice': 'echo',
        'style': 'empathetic',
        'greetings': [
            'Hello, this is Sam from Zero Voice. I\'m here to listen and help.',
            'Hi there, Sam speaking. How are you feeling today?',
            'Welcome, this is Sam. I\'m here for whatever you need.'
        ],
        'responses': [
            'I completely understand how you feel. Let\'s work through this.',
            'That must be challenging. I\'m here to support you.',
            'I hear you. Your concerns are valid, and I want to help.'
        ],
        'closings': [
            'Take care of yourself. Remember, we\'re always here if you need us.',
            'Thank you for sharing with me. Wishing you all the best.',
            'It\'s been meaningful talking with you. Be well.'
        ]
    }
}

def update_call_status(call_sid, status):
    """Update call status in database"""
    try:
        conn = sqlite3.connect(DB_PATH)
        c = conn.cursor()
        c.execute('''
            UPDATE calls
            SET status = ?, updated_at = ?
            WHERE id = ?
        ''', (status, datetime.now().isoformat(), call_sid))
        conn.commit()
        conn.close()
    except Exception as e:
        print(f"Error updating call status: {e}")

def add_transcript_entry(call_sid, speaker, text):
    """Add transcript entry to database"""
    try:
        conn = sqlite3.connect(DB_PATH)
        c = conn.cursor()
        c.execute('''
            INSERT INTO transcript_entries (call_id, speaker, text, timestamp)
            VALUES (?, ?, ?, ?)
        ''', (call_sid, speaker, text, datetime.now().isoformat()))
        conn.commit()
        conn.close()
    except Exception as e:
        print(f"Error adding transcript: {e}")

def get_call_personality(call_sid):
    """Get the personality assigned to this call"""
    try:
        conn = sqlite3.connect(DB_PATH)
        c = conn.cursor()
        c.execute('SELECT agent_personality FROM calls WHERE id = ?', (call_sid,))
        result = c.fetchone()
        conn.close()
        return result[0] if result else 'Alex'
    except:
        return 'Alex'

def generate_ai_response(user_input, personality_name='Alex', context=None):
    """Generate AI response based on personality and input"""
    personality = PERSONALITIES.get(personality_name, PERSONALITIES['Alex'])

    # Simple keyword-based response selection
    user_input_lower = user_input.lower()

    # Greeting detection
    if any(word in user_input_lower for word in ['hello', 'hi', 'hey', 'good morning', 'good afternoon']):
        return random.choice(personality['greetings'])

    # Closing detection
    if any(word in user_input_lower for word in ['bye', 'goodbye', 'thank you', 'thanks']):
        return random.choice(personality['closings'])

    # Help/support detection
    if any(word in user_input_lower for word in ['help', 'problem', 'issue', 'question', 'support']):
        return random.choice(personality['responses'])

    # Default conversational response
    responses = [
        f"I understand you're asking about '{user_input}'. Let me help you with that.",
        f"That's an interesting point about '{user_input}'. Here's what I can tell you.",
        f"Thanks for bringing up '{user_input}'. I'd be happy to assist.",
        "Could you tell me a bit more about what you're looking for?",
        "I'm here to help. What specific information do you need?"
    ]

    # Add personality flair
    if personality_name == 'Jamie':
        responses = [r.replace('.', '!').replace('I understand', 'Oh, I see') for r in responses]
    elif personality_name == 'Sam':
        responses = [r.replace('I understand', 'I hear you and understand') for r in responses]

    return random.choice(responses)

@app.route('/answer/<session_id>', methods=['POST'])
def answer_call(session_id):
    """Handle incoming call answer"""
    call_sid = request.form.get('CallSid', session_id)
    from_number = request.form.get('From', 'Unknown')
    to_number = request.form.get('To', 'Unknown')

    # Update call status
    update_call_status(call_sid, 'answered')

    # Get personality for this call
    personality_name = get_call_personality(call_sid)
    personality = PERSONALITIES.get(personality_name, PERSONALITIES['Alex'])

    # Generate initial greeting
    greeting = random.choice(personality['greetings'])
    add_transcript_entry(call_sid, f'Agent ({personality_name})', greeting)

    # Return TwiML response
    twiml = f'''<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Say voice="{personality['voice']}">{greeting}</Say>
    <Gather input="speech" timeout="5" action="/gather/{call_sid}">
        <Say>Please tell me how I can help you today.</Say>
    </Gather>
    <Say>Thank you for calling. Goodbye!</Say>
</Response>'''

    return Response(twiml, mimetype='text/xml')

@app.route('/gather/<session_id>', methods=['POST'])
def gather_speech(session_id):
    """Handle speech input from caller"""
    call_sid = request.form.get('CallSid', session_id)
    speech_result = request.form.get('SpeechResult', '')

    # Log caller input
    if speech_result:
        add_transcript_entry(call_sid, 'Caller', speech_result)

    # Get personality for this call
    personality_name = get_call_personality(call_sid)
    personality = PERSONALITIES.get(personality_name, PERSONALITIES['Alex'])

    # Generate AI response
    ai_response = generate_ai_response(speech_result, personality_name)
    add_transcript_entry(call_sid, f'Agent ({personality_name})', ai_response)

    # Check if conversation should end
    should_end = any(word in speech_result.lower() for word in ['bye', 'goodbye', 'end call', 'hang up'])

    if should_end:
        closing = random.choice(personality['closings'])
        twiml = f'''<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Say voice="{personality['voice']}">{ai_response}</Say>
    <Say voice="{personality['voice']}">{closing}</Say>
</Response>'''
    else:
        # Continue conversation
        twiml = f'''<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Say voice="{personality['voice']}">{ai_response}</Say>
    <Gather input="speech" timeout="5" action="/gather/{call_sid}">
        <Say>Is there anything else I can help you with?</Say>
    </Gather>
    <Say>Thank you for calling. Goodbye!</Say>
</Response>'''

    return Response(twiml, mimetype='text/xml')

@app.route('/status', methods=['POST'])
def call_status():
    """Handle call status updates"""
    call_sid = request.form.get('CallSid')
    call_status = request.form.get('CallStatus')
    duration = request.form.get('CallDuration', '0')

    if call_sid and call_status:
        # Update call status
        update_call_status(call_sid, call_status)

        # Update duration if call completed
        if call_status == 'completed' and duration:
            try:
                conn = sqlite3.connect(DB_PATH)
                c = conn.cursor()
                c.execute('''
                    UPDATE calls
                    SET duration_seconds = ?, updated_at = ?
                    WHERE id = ?
                ''', (int(duration), datetime.now().isoformat(), call_sid))
                conn.commit()
                conn.close()
            except Exception as e:
                print(f"Error updating call duration: {e}")

    return Response('', status=204)

@app.route('/stream/<session_id>', methods=['POST', 'GET'])
def stream_audio(session_id):
    """Handle streaming audio (placeholder for WebSocket upgrade)"""
    return Response('Streaming endpoint placeholder', status=200)

@app.route('/health')
def health_check():
    """Health check endpoint"""
    return {'status': 'healthy', 'service': 'webhook-server'}

@app.route('/')
def index():
    """Root endpoint"""
    return '''
    <html>
    <head><title>Zero Voice Webhook Server</title></head>
    <body style="font-family: sans-serif; padding: 2rem;">
        <h1>🎯 Zero Voice Webhook Server</h1>
        <p>This server handles Twilio webhooks for Zero Voice conversations.</p>
        <h3>Available Endpoints:</h3>
        <ul>
            <li><code>/answer/{session_id}</code> - Answer incoming calls</li>
            <li><code>/gather/{session_id}</code> - Process speech input</li>
            <li><code>/status</code> - Receive call status updates</li>
            <li><code>/stream/{session_id}</code> - Stream audio (WebSocket)</li>
            <li><code>/health</code> - Health check</li>
        </ul>
        <p><strong>Status:</strong> ✅ Running</p>
    </body>
    </html>
    '''

if __name__ == '__main__':
    print("\n" + "="*60)
    print("🎯 ZERO VOICE WEBHOOK SERVER")
    print("="*60)
    print(f"📊 Database: {DB_PATH}")
    print(f"🌐 Server: http://localhost:3000")
    print("🔗 Endpoints:")
    print("   - /answer/{session_id}")
    print("   - /gather/{session_id}")
    print("   - /status")
    print("="*60 + "\n")

    app.run(host='0.0.0.0', port=3000, debug=True)