#!/usr/bin/env python3
"""
LLMass Web Dashboard - Web GUI for all LLMass commands
"""
import os
import sys
import subprocess
import threading
from flask import Flask, render_template_string, request, jsonify, Response
from dotenv import load_dotenv
import time

load_dotenv()

app = Flask(__name__)

# Command outputs storage
command_outputs = {}
command_status = {}

HTML_TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
    <title>LLMass Web Dashboard</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        .header {
            text-align: center;
            color: white;
            margin-bottom: 40px;
        }
        .header h1 {
            font-size: 48px;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }
        .header p {
            font-size: 18px;
            opacity: 0.9;
        }
        .config-panel {
            background: white;
            border-radius: 12px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.3);
        }
        .config-title {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 20px;
            color: #333;
            border-bottom: 3px solid #667eea;
            padding-bottom: 10px;
        }
        .config-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }
        .config-item {
            display: flex;
            flex-direction: column;
        }
        .config-item label {
            font-weight: 600;
            margin-bottom: 5px;
            color: #555;
            font-size: 14px;
        }
        .config-item input,
        .config-item select {
            padding: 10px;
            border: 2px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
            transition: border-color 0.3s;
        }
        .config-item input:focus,
        .config-item select:focus {
            outline: none;
            border-color: #667eea;
        }
        .commands-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
        }
        .command-card {
            background: white;
            border-radius: 12px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.3);
            transition: transform 0.3s, box-shadow 0.3s;
            cursor: pointer;
        }
        .command-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 40px rgba(0,0,0,0.4);
        }
        .command-icon {
            font-size: 48px;
            margin-bottom: 15px;
        }
        .command-title {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 10px;
            color: #333;
        }
        .command-desc {
            color: #666;
            margin-bottom: 15px;
            line-height: 1.5;
        }
        .command-params {
            margin: 15px 0;
            display: none;
        }
        .command-params.active {
            display: block;
        }
        .param-input {
            margin: 10px 0;
        }
        .param-input label {
            display: block;
            font-weight: 600;
            margin-bottom: 5px;
            color: #555;
            font-size: 13px;
        }
        .param-input input {
            width: 100%;
            padding: 8px;
            border: 2px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
        }
        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 6px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            width: 100%;
            margin-top: 10px;
        }
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        .btn-primary:hover {
            transform: scale(1.05);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        .btn-primary:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }
        .output-panel {
            background: #1e1e1e;
            color: #d4d4d4;
            border-radius: 12px;
            padding: 20px;
            margin-top: 20px;
            font-family: 'Courier New', monospace;
            font-size: 13px;
            line-height: 1.6;
            max-height: 400px;
            overflow-y: auto;
            box-shadow: 0 10px 30px rgba(0,0,0,0.3);
            display: none;
        }
        .output-panel.active {
            display: block;
        }
        .output-line {
            white-space: pre-wrap;
            word-wrap: break-word;
        }
        .status-badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
            margin-top: 10px;
        }
        .status-running {
            background: #ffc107;
            color: #000;
        }
        .status-success {
            background: #28a745;
            color: white;
        }
        .status-error {
            background: #dc3545;
            color: white;
        }
        .spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            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>🚀 LLMass Web Dashboard</h1>
            <p>Zarządzaj wszystkimi funkcjami LLMass z jednego miejsca</p>
        </div>

        <div class="config-panel">
            <div class="config-title">⚙️ Konfiguracja</div>
            <div class="config-grid">
                <div class="config-item">
                    <label>Email Address:</label>
                    <input type="email" id="email-address" value="{{ email_address }}">
                </div>
                <div class="config-item">
                    <label>Email Password:</label>
                    <input type="password" id="email-password" value="{{ password }}">
                </div>
                <div class="config-item">
                    <label>IMAP Server:</label>
                    <input type="text" id="imap-server" value="{{ imap_server }}" placeholder="Auto-detect">
                </div>
            </div>
        </div>

        <div class="commands-grid">
            <div class="command-card" onclick="toggleCommand('clean')">
                <div class="command-icon">🧹</div>
                <div class="command-title">Clean & Organize</div>
                <div class="command-desc">Organizuj i kategoryzuj emaile używając AI</div>
                <div class="command-params" id="params-clean">
                    <div class="param-input">
                        <label>Limit:</label>
                        <input type="number" id="clean-limit" value="50">
                    </div>
                    <div class="param-input">
                        <label>Since Days:</label>
                        <input type="number" id="clean-since-days" value="30">
                    </div>
                    <div class="param-input">
                        <label>Folder:</label>
                        <input type="text" id="clean-folder" value="INBOX">
                    </div>
                </div>
                <button class="btn btn-primary" onclick="runCommand('clean', event)">
                    🚀 Run Clean
                </button>
                <div id="status-clean"></div>
            </div>

            <div class="command-card" onclick="toggleCommand('write')">
                <div class="command-icon">✍️</div>
                <div class="command-title">AI Responder</div>
                <div class="command-desc">Generuj inteligentne odpowiedzi na emaile</div>
                <div class="command-params" id="params-write">
                    <div class="param-input">
                        <label>Limit:</label>
                        <input type="number" id="write-limit" value="5">
                    </div>
                    <div class="param-input">
                        <label>Since Days:</label>
                        <input type="number" id="write-since-days" value="30">
                    </div>
                    <div class="param-input">
                        <label>Dry Run:</label>
                        <select id="write-dry-run">
                            <option value="false">No</option>
                            <option value="true">Yes</option>
                        </select>
                    </div>
                </div>
                <button class="btn btn-primary" onclick="runCommand('write', event)">
                    🚀 Run Responder
                </button>
                <div id="status-write"></div>
            </div>

            <div class="command-card" onclick="toggleCommand('unsubscribe')">
                <div class="command-icon">📧</div>
                <div class="command-title">Unsubscribe Bot</div>
                <div class="command-desc">Automatycznie wypisz się z newsletterów</div>
                <div class="command-params" id="params-unsubscribe">
                    <div class="param-input">
                        <label>Limit:</label>
                        <input type="number" id="unsubscribe-limit" value="50">
                    </div>
                    <div class="param-input">
                        <label>Folder:</label>
                        <input type="text" id="unsubscribe-folder" value="INBOX.Spam">
                    </div>
                    <div class="param-input">
                        <label>Open in Browser:</label>
                        <select id="unsubscribe-open-browser">
                            <option value="false">No</option>
                            <option value="true">Yes</option>
                        </select>
                    </div>
                </div>
                <button class="btn btn-primary" onclick="runCommand('unsubscribe', event)">
                    🚀 Run Unsubscribe
                </button>
                <div id="status-unsubscribe"></div>
            </div>

            <div class="command-card" onclick="toggleCommand('spam-ui')">
                <div class="command-icon">🗑️</div>
                <div class="command-title">Spam Manager UI</div>
                <div class="command-desc">Otwórz interfejs do zarządzania spamem</div>
                <button class="btn btn-primary" onclick="openSpamUI(event)">
                    🚀 Open Spam UI
                </button>
            </div>

            <div class="command-card" onclick="toggleCommand('generate')">
                <div class="command-icon">📨</div>
                <div class="command-title">Generate Test Emails</div>
                <div class="command-desc">Wygeneruj testowe emaile do skrzynki</div>
                <div class="command-params" id="params-generate">
                    <div class="param-input">
                        <label>Count:</label>
                        <input type="number" id="generate-count" value="10">
                    </div>
                </div>
                <button class="btn btn-primary" onclick="runCommand('generate', event)">
                    🚀 Run Generator
                </button>
                <div id="status-generate"></div>
            </div>

            <div class="command-card" onclick="toggleCommand('repair')">
                <div class="command-icon">🔧</div>
                <div class="command-title">Repair Folders</div>
                <div class="command-desc">Napraw strukturę folderów IMAP</div>
                <button class="btn btn-primary" onclick="runCommand('repair', event)">
                    🚀 Run Repair
                </button>
                <div id="status-repair"></div>
            </div>
        </div>

        <div class="output-panel" id="output-panel">
            <div id="output-content"></div>
        </div>
    </div>

    <script>
        let currentCommand = null;
        let pollInterval = null;

        function toggleCommand(cmd) {
            const params = document.getElementById(`params-${cmd}`);
            if (params) {
                params.classList.toggle('active');
            }
        }

        async function runCommand(cmd, event) {
            event.stopPropagation();
            
            if (currentCommand) {
                alert('Please wait for the current command to finish');
                return;
            }

            currentCommand = cmd;
            const statusDiv = document.getElementById(`status-${cmd}`);
            const outputPanel = document.getElementById('output-panel');
            const outputContent = document.getElementById('output-content');
            
            // Show running status
            statusDiv.innerHTML = '<span class="status-badge status-running">Running<div class="spinner"></div></span>';
            outputPanel.classList.add('active');
            outputContent.innerHTML = '<div class="output-line">🚀 Starting command: ' + cmd + '</div>';

            // Gather parameters
            const params = {
                email: document.getElementById('email-address').value,
                password: document.getElementById('email-password').value,
                imap_server: document.getElementById('imap-server').value,
            };

            // Command-specific parameters
            if (cmd === 'clean') {
                params.limit = document.getElementById('clean-limit').value;
                params.since_days = document.getElementById('clean-since-days').value;
                params.folder = document.getElementById('clean-folder').value;
            } else if (cmd === 'write') {
                params.limit = document.getElementById('write-limit').value;
                params.since_days = document.getElementById('write-since-days').value;
                params.dry_run = document.getElementById('write-dry-run').value === 'true';
            } else if (cmd === 'unsubscribe') {
                params.limit = document.getElementById('unsubscribe-limit').value;
                params.folder = document.getElementById('unsubscribe-folder').value;
                params.open_browser = document.getElementById('unsubscribe-open-browser').value === 'true';
            } else if (cmd === 'generate') {
                params.count = document.getElementById('generate-count').value;
            }

            try {
                const response = await fetch('/api/run', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ command: cmd, params: params })
                });

                const result = await response.json();
                
                if (result.success) {
                    // Start polling for output
                    pollInterval = setInterval(() => pollOutput(cmd), 1000);
                } else {
                    statusDiv.innerHTML = '<span class="status-badge status-error">Error</span>';
                    outputContent.innerHTML += '<div class="output-line">❌ Error: ' + result.error + '</div>';
                    currentCommand = null;
                }
            } catch (error) {
                console.error('Error running command:', error);
                statusDiv.innerHTML = '<span class="status-badge status-error">Error</span>';
                outputContent.innerHTML += '<div class="output-line">❌ Error: ' + error + '</div>';
                currentCommand = null;
            }
        }

        async function pollOutput(cmd) {
            try {
                const response = await fetch(`/api/output/${cmd}`);
                const result = await response.json();
                
                const outputContent = document.getElementById('output-content');
                outputContent.innerHTML = result.output.split('\\n').map(line => 
                    `<div class="output-line">${escapeHtml(line)}</div>`
                ).join('');
                
                // Scroll to bottom
                const panel = document.getElementById('output-panel');
                panel.scrollTop = panel.scrollHeight;

                if (result.status === 'completed' || result.status === 'error') {
                    clearInterval(pollInterval);
                    pollInterval = null;
                    currentCommand = null;
                    
                    const statusDiv = document.getElementById(`status-${cmd}`);
                    if (result.status === 'completed') {
                        statusDiv.innerHTML = '<span class="status-badge status-success">✅ Completed</span>';
                    } else {
                        statusDiv.innerHTML = '<span class="status-badge status-error">❌ Error</span>';
                    }
                }
            } catch (error) {
                console.error('Error polling output:', error);
            }
        }

        function openSpamUI(event) {
            event.stopPropagation();
            window.open('http://localhost:5001', '_blank');
        }

        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // Auto-load on page load
        window.addEventListener('load', () => {
            console.log('Dashboard loaded');
        });
    </script>
</body>
</html>
"""


@app.route('/')
def index():
    """Main dashboard page."""
    return render_template_string(
        HTML_TEMPLATE,
        email_address=os.getenv('EMAIL_ADDRESS', ''),
        password=os.getenv('EMAIL_PASSWORD', ''),
        imap_server=os.getenv('IMAP_SERVER', '')
    )


@app.route('/api/run', methods=['POST'])
def api_run():
    """Run a command in the background."""
    data = request.json
    command = data.get('command')
    params = data.get('params', {})
    
    if not command:
        return jsonify({'success': False, 'error': 'No command specified'})
    
    # Build command line
    cmd_args = ['llmass', command]
    
    # Add parameters
    if params.get('email'):
        cmd_args.extend(['--email', params['email']])
    if params.get('password'):
        cmd_args.extend(['--password', params['password']])
    if params.get('imap_server'):
        cmd_args.extend(['--server', params['imap_server']])
    
    if command == 'clean':
        if params.get('limit'):
            cmd_args.extend(['--limit', str(params['limit'])])
        if params.get('since_days'):
            cmd_args.extend(['--since-days', str(params['since_days'])])
        if params.get('folder'):
            cmd_args.extend(['--folder', params['folder']])
    elif command == 'write':
        if params.get('limit'):
            cmd_args.extend(['--limit', str(params['limit'])])
        if params.get('since_days'):
            cmd_args.extend(['--since-days', str(params['since_days'])])
        if params.get('dry_run'):
            cmd_args.append('--dry-run')
    elif command == 'unsubscribe':
        if params.get('limit'):
            cmd_args.extend(['--limit', str(params['limit'])])
        if params.get('folder'):
            cmd_args.extend(['--folder', params['folder']])
        if params.get('open_browser'):
            cmd_args.append('--open-browser')
    elif command == 'generate':
        if params.get('count'):
            cmd_args.extend(['--count', str(params['count'])])
    
    # Run command in background thread
    def run_subprocess():
        try:
            command_status[command] = 'running'
            command_outputs[command] = ''
            
            process = subprocess.Popen(
                cmd_args,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                text=True,
                bufsize=1
            )
            
            for line in process.stdout:
                command_outputs[command] += line
            
            process.wait()
            
            if process.returncode == 0:
                command_status[command] = 'completed'
            else:
                command_status[command] = 'error'
                command_outputs[command] += f"\\n❌ Command exited with code {process.returncode}"
        except Exception as e:
            command_status[command] = 'error'
            command_outputs[command] += f"\\n❌ Error: {str(e)}"
    
    thread = threading.Thread(target=run_subprocess, daemon=True)
    thread.start()
    
    return jsonify({'success': True})


@app.route('/api/output/<command>')
def api_output(command):
    """Get command output."""
    output = command_outputs.get(command, '')
    status = command_status.get(command, 'unknown')
    
    return jsonify({
        'output': output,
        'status': status
    })


def main():
    """Main entry point."""
    print("🚀 Starting LLMass Web Dashboard...")
    print("📧 Email:", os.getenv('EMAIL_ADDRESS', 'Not set'))
    print("🌐 URL: http://0.0.0.0:5002")
    print("")
    print("💡 Otwórz w przeglądarce: http://localhost:5002")
    print("   Ctrl+C aby zatrzymać")
    print("")
    
    app.run(host='0.0.0.0', port=5002, debug=False)


if __name__ == '__main__':
    main()
