<!DOCTYPE html>
<html lang="en" data-bs-theme="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AIVim - AI-Enhanced Text Editor</title>
    <link rel="stylesheet" href="https://cdn.replit.com/agent/bootstrap-agent-dark-theme.min.css">
    <style>
        .editor-container {
            height: 70vh;
            display: flex;
            flex-direction: column;
        }
        
        .editor-section {
            flex: 1;
            display: flex;
            gap: 1rem;
        }
        
        .code-editor {
            flex: 1;
            border: 1px solid var(--bs-gray-700);
            border-radius: 0.25rem;
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }
        
        .code-editor textarea {
            flex: 1;
            resize: none;
            background-color: var(--bs-gray-900);
            color: var(--bs-gray-200);
            border: none;
            padding: 1rem;
            font-family: 'Courier New', monospace;
            font-size: 14px;
            line-height: 1.5;
        }
        
        .output-area {
            flex: 1;
            border: 1px solid var(--bs-gray-700);
            border-radius: 0.25rem;
            background-color: var(--bs-gray-900);
            padding: 1rem;
            overflow-y: auto;
            font-family: 'Courier New', monospace;
            color: var(--bs-gray-200);
            white-space: pre-wrap;
        }
        
        .action-bar {
            display: flex;
            gap: 0.5rem;
            padding: 0.5rem 0;
        }
        
        .api-key-alert {
            margin-top: 1rem;
        }
        
        .loading {
            display: none;
            align-items: center;
            gap: 0.5rem;
            margin-left: 1rem;
        }
        
        .spinner-border {
            width: 1rem;
            height: 1rem;
        }
        
        .markdown code {
            background-color: var(--bs-gray-800);
            padding: 0.2rem 0.4rem;
            border-radius: 0.25rem;
        }
        
        .markdown pre {
            background-color: var(--bs-gray-800);
            padding: 1rem;
            border-radius: 0.25rem;
            overflow-x: auto;
        }
        
        .markdown h1, .markdown h2, .markdown h3 {
            margin-top: 1.5rem;
            margin-bottom: 0.75rem;
        }
    </style>
</head>
<body>
    <div class="container py-4">
        <header class="pb-3 mb-4 border-bottom">
            <div class="d-flex align-items-center">
                <h1 class="me-3">AIVim</h1>
                <span class="fs-5 text-secondary">AI-Enhanced Text Editor (Web Interface)</span>
            </div>
        </header>

        <div class="row mb-4">
            <div class="col-12">
                <div class="p-4 bg-body-secondary rounded-3">
                    <h2>Welcome to AIVim</h2>
                    <p>
                        AIVim is an AI-enhanced text editor built with Python that provides intelligent 
                        code assistance. This web interface allows you to try some of AIVim's 
                        AI features without installing the full terminal application.
                    </p>
                    <div id="api-key-alert" class="alert alert-warning api-key-alert d-none">
                        <strong>API Key Missing:</strong> AI features require an OpenAI API key. 
                        Please set the <code>OPENAI_API_KEY</code> environment variable to use AI capabilities.
                    </div>
                    <div id="model-info" class="alert alert-info api-key-alert">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <strong>Current Model:</strong> <span id="current-model">Loading...</span>
                            </div>
                            <div>
                                <label for="model-selector" class="me-2">Select AI Model:</label>
                                <select id="model-selector" class="form-select form-select-sm" style="width: auto; display: inline-block;">
                                    <option value="openai">OpenAI</option>
                                    <option value="claude">Claude</option>
                                    <option value="local">Local LLM</option>
                                </select>
                            </div>
                        </div>
                        <div id="config-status" class="mt-2"></div>
                    </div>
                </div>
            </div>
        </div>

        <div class="editor-container mb-4">
            <div class="action-bar">
                <select id="action-select" class="form-select" style="width: auto;">
                    <option value="explain">Explain Code</option>
                    <option value="improve">Improve Code</option>
                    <option value="generate">Generate Code</option>
                    <option value="query">Custom Query</option>
                    <option value="analyze">Analyze Code</option>
                </select>
                <div id="specification-container" class="d-none" style="flex-grow: 1;">
                    <textarea id="specification-input" class="form-control" 
                        placeholder="Enter code specification (up to 1000 characters)..." 
                        rows="4" style="resize: vertical; min-height: 80px; max-height: 200px;"></textarea>
                </div>
                <div id="query-container" class="d-none" style="flex-grow: 1;">
                    <textarea id="query-input" class="form-control" 
                        placeholder="Ask a question about the code..." 
                        rows="3" style="resize: vertical; min-height: 60px; max-height: 150px;"></textarea>
                </div>
                <button id="execute-btn" class="btn btn-primary">Execute</button>
                <div id="loading" class="loading">
                    <span class="spinner-border" role="status"></span>
                    <span>Processing...</span>
                </div>
            </div>
            
            <div class="editor-section">
                <div class="code-editor">
                    <div class="p-2 bg-body-tertiary border-bottom">
                        <span>Code Editor</span>
                    </div>
                    <textarea id="code-editor" placeholder="Enter your code here..." spellcheck="false">def calculate_factorial(n):
    # Calculate the factorial of a number using a recursive approach
    if n == 0 or n == 1:
        return 1
    else:
        return n * calculate_factorial(n - 1)

def main():
    # Get input from user
    try:
        num = int(input("Enter a number: "))
        if num < 0:
            print("Factorial is not defined for negative numbers")
        else:
            result = calculate_factorial(num)
            print(f"The factorial of {num} is {result}")
    except ValueError:
        print("Invalid input. Please enter a valid number.")

if __name__ == "__main__":
    main()
</textarea>
                </div>
                
                <div class="code-editor">
                    <div class="p-2 bg-body-tertiary border-bottom">
                        <span>Output</span>
                        <button id="clear-output-btn" class="btn btn-sm btn-outline-secondary float-end">Clear</button>
                    </div>
                    <div id="output-area" class="output-area markdown"></div>
                </div>
            </div>
        </div>
        
        <div class="row">
            <div class="col-12">
                <div class="p-4 bg-body-secondary rounded-3">
                    <h2>Available Features</h2>
                    <ul>
                        <li><strong>Explain Code:</strong> Get a detailed explanation of the code you've entered</li>
                        <li><strong>Improve Code:</strong> Get suggestions on how to improve your code</li>
                        <li><strong>Generate Code:</strong> Generate code based on a natural language description</li>
                        <li><strong>Custom Query:</strong> Ask specific questions about the code</li>
                        <li><strong>Analyze Code:</strong> Get an analysis of code complexity and potential bugs</li>
                    </ul>
                    <p class="mt-3">
                        For the full terminal-based AIVim experience with modal editing and more features, 
                        use the command-line application: <code>python run_editor.py file.py</code>
                    </p>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const actionSelect = document.getElementById('action-select');
            const codeEditor = document.getElementById('code-editor');
            const outputArea = document.getElementById('output-area');
            const executeBtn = document.getElementById('execute-btn');
            const clearOutputBtn = document.getElementById('clear-output-btn');
            const specificationContainer = document.getElementById('specification-container');
            const specificationInput = document.getElementById('specification-input');
            const queryContainer = document.getElementById('query-container');
            const queryInput = document.getElementById('query-input');
            const loadingIndicator = document.getElementById('loading');
            const apiKeyAlert = document.getElementById('api-key-alert');
            
            // Check if API key is set
            fetch('/api/check-api-key')
                .then(response => response.json())
                .then(data => {
                    if (!data.has_key) {
                        apiKeyAlert.classList.remove('d-none');
                    }
                })
                .catch(error => {
                    console.error('Error checking API key:', error);
                    apiKeyAlert.classList.remove('d-none');
                });
                
            // Get model information
            const currentModelSpan = document.getElementById('current-model');
            const configStatusDiv = document.getElementById('config-status');
            const modelSelector = document.getElementById('model-selector');
            
            // Function to update model information display
            function updateModelInfo() {
                fetch('/api/model-info')
                    .then(response => response.json())
                    .then(data => {
                        // Update model information
                        currentModelSpan.textContent = data.model;
                        
                        // Set the current model in the selector
                        if (data.model.toLowerCase().includes('openai')) {
                            modelSelector.value = 'openai';
                        } else if (data.model.toLowerCase().includes('claude')) {
                            modelSelector.value = 'claude';
                        } else if (data.model.toLowerCase().includes('local')) {
                            modelSelector.value = 'local';
                        }
                        
                        // Show config status
                        if (data.config_status.loaded) {
                            configStatusDiv.innerHTML = `<small class="text-success">Configuration loaded from: ${data.config_status.path}</small>`;
                        } else if (data.is_configured) {
                            configStatusDiv.innerHTML = `<small class="text-info">Using environment variables for AI configuration</small>`;
                        } else {
                            configStatusDiv.innerHTML = `<small class="text-warning">${data.config_status.message}</small>`;
                        }
                    })
                    .catch(error => {
                        console.error('Error fetching model info:', error);
                        currentModelSpan.textContent = 'Error loading model info';
                        configStatusDiv.innerHTML = `<small class="text-danger">Could not retrieve model information</small>`;
                    });
            }
            
            // Call initially to set up the display
            updateModelInfo();
            
            // Handle model selection changes
            modelSelector.addEventListener('change', function() {
                const selectedModel = this.value;
                
                // Show loading state
                currentModelSpan.textContent = 'Switching model...';
                modelSelector.disabled = true;
                
                // Send request to change the model
                fetch('/api/set-model', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ model: selectedModel })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Update the UI with the new model info
                        updateModelInfo();
                    } else {
                        throw new Error(data.message || 'Failed to change model');
                    }
                })
                .catch(error => {
                    console.error('Error changing model:', error);
                    currentModelSpan.textContent = 'Error changing model';
                    configStatusDiv.innerHTML = `<small class="text-danger">Error: ${error.message}</small>`;
                })
                .finally(() => {
                    modelSelector.disabled = false;
                });
            });
            
            // Handle action selection changes
            actionSelect.addEventListener('change', function() {
                if (this.value === 'generate') {
                    specificationContainer.classList.remove('d-none');
                    queryContainer.classList.add('d-none');
                } else if (this.value === 'query') {
                    queryContainer.classList.remove('d-none');
                    specificationContainer.classList.add('d-none');
                } else {
                    specificationContainer.classList.add('d-none');
                    queryContainer.classList.add('d-none');
                }
            });
            
            // Handle executing AI actions
            executeBtn.addEventListener('click', function() {
                const action = actionSelect.value;
                const code = codeEditor.value;
                
                if (!code.trim()) {
                    outputArea.innerHTML = 'Please enter some code first.';
                    return;
                }
                
                // Prepare request data
                const requestData = {
                    action: action,
                    code: code,
                    context: code
                };
                
                // Add specification if it's a generate action
                if (action === 'generate') {
                    if (!specificationInput.value.trim()) {
                        outputArea.innerHTML = 'Please enter a specification for code generation.';
                        return;
                    }
                    requestData.specification = specificationInput.value;
                }
                
                // Add query if it's a query action
                if (action === 'query') {
                    if (!queryInput.value.trim()) {
                        outputArea.innerHTML = 'Please enter a query about the code.';
                        return;
                    }
                    requestData.query = queryInput.value;
                }
                
                // Show loading indicator
                loadingIndicator.style.display = 'flex';
                executeBtn.disabled = true;
                
                // Make API request
                fetch('/api/ai-assist', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestData)
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    // Format the result as markdown
                    outputArea.innerHTML = marked.parse(data.result);
                })
                .catch(error => {
                    console.error('Error:', error);
                    outputArea.innerHTML = `Error: ${error.message}`;
                })
                .finally(() => {
                    // Hide loading indicator
                    loadingIndicator.style.display = 'none';
                    executeBtn.disabled = false;
                });
            });
            
            // Clear output button
            clearOutputBtn.addEventListener('click', function() {
                outputArea.innerHTML = '';
            });
        });
    </script>
</body>
</html>