#!/usr/bin/env python3
"""
Zero Voice Simple Dashboard - Fully Functional with Real Twilio Integration
This dashboard allows you to make real phone calls using your Twilio credentials.
"""

import os
import json
import sqlite3
import requests
from datetime import datetime, timedelta
from flask import Flask, render_template_string, jsonify, request
from flask_cors import CORS
from dotenv import load_dotenv
import base64
from urllib.parse import urlencode

# Load environment variables
load_dotenv()

app = Flask(__name__)
CORS(app)

# Configuration from environment
TWILIO_ACCOUNT_SID = os.getenv('TWILIO_ACCOUNT_SID')
TWILIO_AUTH_TOKEN = os.getenv('TWILIO_AUTH_TOKEN')
TWILIO_PHONE_NUMBER = os.getenv('TWILIO_PHONE_NUMBER')
WEBHOOK_BASE_URL = os.getenv('WEBHOOK_BASE_URL', 'http://localhost:3000')
DATABASE_URL = os.getenv('DATABASE_URL', 'sqlite:///app/data/zero_voice.db')

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

# Ensure data directory exists
os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)

def init_database():
    """Initialize database with required tables"""
    conn = sqlite3.connect(DB_PATH)
    c = conn.cursor()

    # Create calls table
    c.execute('''
        CREATE TABLE IF NOT EXISTS calls (
            id TEXT PRIMARY KEY,
            from_number TEXT NOT NULL,
            to_number TEXT NOT NULL,
            status TEXT NOT NULL,
            direction TEXT,
            duration_seconds INTEGER DEFAULT 0,
            recording_url TEXT,
            transcript TEXT,
            ai_summary TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            campaign_id TEXT,
            agent_personality TEXT,
            objectives_completed TEXT,
            sentiment_score REAL
        )
    ''')

    # Create transcript_entries table
    c.execute('''
        CREATE TABLE IF NOT EXISTS transcript_entries (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            call_id TEXT NOT NULL,
            speaker TEXT NOT NULL,
            text TEXT NOT NULL,
            timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            sentiment TEXT,
            intent TEXT,
            FOREIGN KEY (call_id) REFERENCES calls(id)
        )
    ''')

    conn.commit()
    conn.close()

def make_twilio_call(to_number, message, personality='Alex'):
    """Make a real Twilio phone call"""
    if not all([TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, TWILIO_PHONE_NUMBER]):
        return {'error': 'Twilio credentials not configured'}

    # Clean up webhook URL
    webhook_url = WEBHOOK_BASE_URL
    if webhook_url == 'https://your-ngrok-subdomain.ngrok.io':
        # Use local webhook server
        webhook_url = 'http://webhook-server:3000'

    # Create TwiML for the call
    twiml = f'''<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Say voice="alice">{message}</Say>
    <Gather input="speech" timeout="5" action="{webhook_url}/gather">
        <Say>Please tell me how I can help you today.</Say>
    </Gather>
    <Say>Thank you for calling. Goodbye!</Say>
</Response>'''

    # Prepare the API request
    url = f"https://api.twilio.com/2010-04-01/Accounts/{TWILIO_ACCOUNT_SID}/Calls.json"

    # Create auth header
    auth = base64.b64encode(f"{TWILIO_ACCOUNT_SID}:{TWILIO_AUTH_TOKEN}".encode()).decode('ascii')

    headers = {
        'Authorization': f'Basic {auth}',
        'Content-Type': 'application/x-www-form-urlencoded'
    }

    data = {
        'To': to_number,
        'From': TWILIO_PHONE_NUMBER,
        'Twiml': twiml,
        'Record': 'true',
        'StatusCallback': f'{webhook_url}/status',
        'StatusCallbackEvent': 'initiated ringing answered completed',
        'StatusCallbackMethod': 'POST'
    }

    try:
        response = requests.post(url, headers=headers, data=data)
        if response.status_code == 201:
            call_data = response.json()

            # Save call to database
            conn = sqlite3.connect(DB_PATH)
            c = conn.cursor()
            c.execute('''
                INSERT INTO calls (id, from_number, to_number, status, direction, agent_personality, created_at)
                VALUES (?, ?, ?, ?, ?, ?, ?)
            ''', (
                call_data['sid'],
                TWILIO_PHONE_NUMBER,
                to_number,
                'initiated',
                'outbound',
                personality,
                datetime.now().isoformat()
            ))
            conn.commit()
            conn.close()

            return {
                'success': True,
                'call_sid': call_data['sid'],
                'status': call_data['status'],
                'message': f'Call initiated to {to_number}'
            }
        else:
            return {
                'error': f'Twilio API error: {response.status_code}',
                'details': response.text
            }
    except Exception as e:
        return {'error': str(e)}

# HTML Template for the dashboard
DASHBOARD_HTML = '''<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Zero Voice - Functional Dashboard</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%);
            min-height: 100vh;
            color: #333;
        }
        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 2rem;
        }
        .header {
            background: white;
            border-radius: 1rem;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }
        .header h1 {
            font-size: 2.5rem;
            color: #667eea;
            margin-bottom: 0.5rem;
        }
        .status-badge {
            display: inline-block;
            padding: 0.5rem 1rem;
            border-radius: 2rem;
            font-size: 0.9rem;
            font-weight: 600;
            margin-right: 1rem;
        }
        .status-active { background: #10b981; color: white; }
        .status-warning { background: #f59e0b; color: white; }
        .grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 2rem;
            margin-bottom: 2rem;
        }
        .card {
            background: white;
            border-radius: 1rem;
            padding: 2rem;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }
        .card h2 {
            color: #667eea;
            margin-bottom: 1.5rem;
            font-size: 1.5rem;
        }
        .stat-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 1rem;
        }
        .stat-item {
            padding: 1rem;
            background: #f3f4f6;
            border-radius: 0.5rem;
        }
        .stat-value {
            font-size: 2rem;
            font-weight: bold;
            color: #667eea;
        }
        .stat-label {
            color: #6b7280;
            font-size: 0.9rem;
            margin-top: 0.25rem;
        }
        .form-group {
            margin-bottom: 1.5rem;
        }
        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            color: #4b5563;
            font-weight: 600;
        }
        .form-control {
            width: 100%;
            padding: 0.75rem;
            border: 2px solid #e5e7eb;
            border-radius: 0.5rem;
            font-size: 1rem;
            transition: border-color 0.3s;
        }
        .form-control:focus {
            outline: none;
            border-color: #667eea;
        }
        .btn {
            padding: 0.75rem 2rem;
            border: none;
            border-radius: 0.5rem;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }
        .btn-primary {
            background: #667eea;
            color: white;
        }
        .btn-primary:hover {
            background: #5a67d8;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        .btn-primary:disabled {
            background: #9ca3af;
            cursor: not-allowed;
            transform: none;
        }
        .call-list {
            max-height: 400px;
            overflow-y: auto;
        }
        .call-item {
            padding: 1rem;
            background: #f9fafb;
            border-radius: 0.5rem;
            margin-bottom: 0.75rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .call-status {
            padding: 0.25rem 0.75rem;
            border-radius: 1rem;
            font-size: 0.85rem;
            font-weight: 600;
        }
        .status-completed { background: #d1fae5; color: #065f46; }
        .status-in-progress { background: #fed7aa; color: #92400e; }
        .status-failed { background: #fee2e2; color: #991b1b; }
        .alert {
            padding: 1rem;
            border-radius: 0.5rem;
            margin-bottom: 1rem;
        }
        .alert-success {
            background: #d1fae5;
            color: #065f46;
            border: 1px solid #a7f3d0;
        }
        .alert-error {
            background: #fee2e2;
            color: #991b1b;
            border: 1px solid #fecaca;
        }
        .personality-selector {
            display: flex;
            gap: 1rem;
            margin-bottom: 1rem;
        }
        .personality-option {
            flex: 1;
            padding: 1rem;
            border: 2px solid #e5e7eb;
            border-radius: 0.5rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
        }
        .personality-option:hover {
            border-color: #667eea;
            background: #f3f4f6;
        }
        .personality-option.selected {
            border-color: #667eea;
            background: #ede9fe;
        }
        .spinner {
            border: 3px solid #f3f4f6;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            animation: spin 1s linear infinite;
            display: inline-block;
            margin-left: 10px;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🎯 Zero Voice - Functional Dashboard</h1>
            <p style="margin-bottom: 1rem;">AI-powered call center with real Twilio integration</p>
            <span class="status-badge status-active">System Active</span>
            <span class="status-badge" id="twilioStatus">Checking Twilio...</span>
        </div>

        <div id="alerts"></div>

        <div class="grid">
            <!-- Make a Call Card -->
            <div class="card">
                <h2>📞 Make a Call</h2>
                <form id="callForm">
                    <div class="form-group">
                        <label for="phoneNumber">Phone Number</label>
                        <input type="tel" id="phoneNumber" class="form-control"
                               placeholder="+1234567890" required>
                    </div>

                    <div class="form-group">
                        <label>Agent Personality</label>
                        <div class="personality-selector">
                            <div class="personality-option selected" data-personality="Alex">
                                <strong>Alex</strong><br>
                                <small>Professional</small>
                            </div>
                            <div class="personality-option" data-personality="Jamie">
                                <strong>Jamie</strong><br>
                                <small>Friendly</small>
                            </div>
                            <div class="personality-option" data-personality="Sam">
                                <strong>Sam</strong><br>
                                <small>Empathetic</small>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="message">Initial Message</label>
                        <textarea id="message" class="form-control" rows="4"
                                  placeholder="Hello! This is a test call from Zero Voice...">Hello! This is Zero Voice, an AI-powered assistant. How can I help you today?</textarea>
                    </div>

                    <button type="submit" class="btn btn-primary" id="callButton">
                        Start Call
                    </button>
                </form>
            </div>

            <!-- Statistics Card -->
            <div class="card">
                <h2>📊 Live Statistics</h2>
                <div class="stat-grid">
                    <div class="stat-item">
                        <div class="stat-value" id="totalCalls">0</div>
                        <div class="stat-label">Total Calls</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value" id="activeCalls">0</div>
                        <div class="stat-label">Active Calls</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value" id="successRate">0%</div>
                        <div class="stat-label">Success Rate</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value" id="avgDuration">0s</div>
                        <div class="stat-label">Avg Duration</div>
                    </div>
                </div>
                <button class="btn btn-primary" style="margin-top: 1rem; width: 100%;"
                        onclick="refreshStats()">Refresh Stats</button>
            </div>
        </div>

        <!-- Recent Calls Card -->
        <div class="card">
            <h2>📋 Recent Calls</h2>
            <div class="call-list" id="callList">
                <p style="color: #9ca3af; text-align: center; padding: 2rem;">No calls yet. Make your first call above!</p>
            </div>
        </div>
    </div>

    <script>
        let selectedPersonality = 'Alex';

        // Personality selector
        document.querySelectorAll('.personality-option').forEach(option => {
            option.addEventListener('click', function() {
                document.querySelectorAll('.personality-option').forEach(o => o.classList.remove('selected'));
                this.classList.add('selected');
                selectedPersonality = this.dataset.personality;
            });
        });

        // Check Twilio status
        async function checkTwilioStatus() {
            try {
                const response = await fetch('/api/twilio-status');
                const data = await response.json();
                const badge = document.getElementById('twilioStatus');
                if (data.configured) {
                    badge.className = 'status-badge status-active';
                    badge.textContent = 'Twilio Connected';
                } else {
                    badge.className = 'status-badge status-warning';
                    badge.textContent = 'Twilio Not Configured';
                }
            } catch (error) {
                console.error('Error checking Twilio status:', error);
            }
        }

        // Show alert
        function showAlert(message, type = 'success') {
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type}`;
            alertDiv.textContent = message;
            document.getElementById('alerts').appendChild(alertDiv);
            setTimeout(() => alertDiv.remove(), 5000);
        }

        // Handle form submission
        document.getElementById('callForm').addEventListener('submit', async (e) => {
            e.preventDefault();

            const button = document.getElementById('callButton');
            const originalText = button.innerHTML;
            button.disabled = true;
            button.innerHTML = 'Initiating Call...<span class="spinner"></span>';

            const phoneNumber = document.getElementById('phoneNumber').value;
            const message = document.getElementById('message').value;

            try {
                const response = await fetch('/api/make-call', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        to_number: phoneNumber,
                        message: message,
                        personality: selectedPersonality
                    })
                });

                const data = await response.json();

                if (data.success) {
                    showAlert(`Call initiated successfully! Call ID: ${data.call_sid}`, 'success');
                    refreshStats();
                    loadRecentCalls();
                } else {
                    showAlert(`Error: ${data.error || 'Failed to initiate call'}`, 'error');
                }
            } catch (error) {
                showAlert(`Error: ${error.message}`, 'error');
            } finally {
                button.disabled = false;
                button.innerHTML = originalText;
            }
        });

        // Refresh statistics
        async function refreshStats() {
            try {
                const response = await fetch('/api/stats');
                const data = await response.json();

                document.getElementById('totalCalls').textContent = data.total_calls || 0;
                document.getElementById('activeCalls').textContent = data.active_calls || 0;
                document.getElementById('successRate').textContent =
                    data.success_rate ? `${data.success_rate.toFixed(1)}%` : '0%';
                document.getElementById('avgDuration').textContent =
                    data.avg_duration ? `${Math.round(data.avg_duration)}s` : '0s';
            } catch (error) {
                console.error('Error loading stats:', error);
            }
        }

        // Load recent calls
        async function loadRecentCalls() {
            try {
                const response = await fetch('/api/recent-calls');
                const calls = await response.json();

                const callList = document.getElementById('callList');

                if (calls.length === 0) {
                    callList.innerHTML = '<p style="color: #9ca3af; text-align: center; padding: 2rem;">No calls yet. Make your first call above!</p>';
                } else {
                    callList.innerHTML = calls.map(call => `
                        <div class="call-item">
                            <div>
                                <strong>${call.to_number}</strong><br>
                                <small>${new Date(call.created_at).toLocaleString()}</small>
                            </div>
                            <span class="call-status status-${call.status}">${call.status}</span>
                        </div>
                    `).join('');
                }
            } catch (error) {
                console.error('Error loading calls:', error);
            }
        }

        // Initialize dashboard
        window.addEventListener('load', () => {
            checkTwilioStatus();
            refreshStats();
            loadRecentCalls();

            // Auto-refresh every 5 seconds
            setInterval(() => {
                refreshStats();
                loadRecentCalls();
            }, 5000);
        });
    </script>
</body>
</html>'''

@app.route('/')
def index():
    return render_template_string(DASHBOARD_HTML)

@app.route('/api/twilio-status')
def twilio_status():
    configured = all([TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, TWILIO_PHONE_NUMBER])
    return jsonify({
        'configured': configured,
        'account_sid': TWILIO_ACCOUNT_SID[:10] + '...' if TWILIO_ACCOUNT_SID else None,
        'phone_number': TWILIO_PHONE_NUMBER if TWILIO_PHONE_NUMBER else None
    })

@app.route('/api/make-call', methods=['POST'])
def api_make_call():
    data = request.json
    result = make_twilio_call(
        data['to_number'],
        data['message'],
        data.get('personality', 'Alex')
    )
    return jsonify(result)

@app.route('/api/stats')
def api_stats():
    conn = sqlite3.connect(DB_PATH)
    c = conn.cursor()

    # Total calls
    c.execute('SELECT COUNT(*) FROM calls')
    total_calls = c.fetchone()[0]

    # Active calls
    c.execute("SELECT COUNT(*) FROM calls WHERE status IN ('initiated', 'ringing', 'in-progress')")
    active_calls = c.fetchone()[0]

    # Success rate
    c.execute("SELECT COUNT(*) FROM calls WHERE status = 'completed'")
    completed_calls = c.fetchone()[0]
    success_rate = (completed_calls / total_calls * 100) if total_calls > 0 else 0

    # Average duration
    c.execute('SELECT AVG(duration_seconds) FROM calls WHERE duration_seconds > 0')
    avg_duration = c.fetchone()[0] or 0

    conn.close()

    return jsonify({
        'total_calls': total_calls,
        'active_calls': active_calls,
        'success_rate': success_rate,
        'avg_duration': avg_duration
    })

@app.route('/api/recent-calls')
def api_recent_calls():
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    c = conn.cursor()

    c.execute('''
        SELECT id, from_number, to_number, status, duration_seconds, created_at, agent_personality
        FROM calls
        ORDER BY created_at DESC
        LIMIT 10
    ''')

    calls = [dict(row) for row in c.fetchall()]
    conn.close()

    return jsonify(calls)

if __name__ == '__main__':
    init_database()
    print("\n" + "="*60)
    print("🚀 ZERO VOICE FUNCTIONAL DASHBOARD")
    print("="*60)
    print(f"📞 Twilio Configured: {'✓' if TWILIO_ACCOUNT_SID else '✗'}")
    print(f"📊 Database: {DB_PATH}")
    print(f"🌐 Dashboard: http://localhost:8080")
    print("="*60 + "\n")

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