{% extends "base.html" %}

{% block content %}


<!-- Create Form (hidden by default) -->
<div class="row mb-4" id="createForm" style="display: none;">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h5><i class="fas fa-plus me-2"></i>Create New Prompt</h5>
            </div>
            <div class="card-body">
                <form method="POST" action="/prompts/create">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="name" class="form-label">Name</label>
                                <input type="text" class="form-control" id="name" name="name" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="description" class="form-label">Description</label>
                                <input type="text" class="form-control" id="description" name="description">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="model" class="form-label">AI Model</label>
                                <select class="form-control" id="model" name="model" required>
                                    <option value="haiku">Haiku (Fast)</option>
                                    <option value="sonnet">Sonnet (Balanced)</option>
                                    <option value="sonnet-3.5">Sonnet 3.5 (Advanced)</option>
                                    <option value="opus">Opus (Most Powerful)</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="persona" class="form-label">Agent Persona</label>
                                <select class="form-control" id="persona" name="persona" required>
                                    <option value="basic_agent">Basic Agent</option>
                                    <option value="deep_research_agent">Deep Research Agent</option>
                                    <option value="autonomous_engineer">Autonomous Engineer</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="prompt_text" class="form-label">Prompt Text</label>
                        <textarea class="form-control" id="prompt_text" name="prompt_text" rows="6" required></textarea>
                    </div>
                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-success">
                            <i class="fas fa-save me-2"></i>Create Prompt
                        </button>
                        <button type="button" class="btn btn-secondary" onclick="hideCreateForm()">
                            <i class="fas fa-times me-2"></i>Cancel
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Prompts List -->
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <h5 class="mb-0"><i class="fas fa-list me-2"></i>Prompts</h5>
                    <button class="btn btn-primary btn-sm" id="showCreateFormBtn" onclick="showCreateForm()">
                        <i class="fas fa-plus me-2"></i>New
                    </button>
                </div>
            </div>
            <div class="card-body">
                {% if prompts %}
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>Name</th>
                                    <th>Description</th>
                                    <th>Model</th>
                                    <th>Persona</th>
                                    <th>Created</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for prompt in prompts %}
                                <tr>
                                    <td><strong>{{ prompt.name }}</strong></td>
                                    <td>{{ prompt.description or '-' }}</td>
                                    <td>
                                        <span class="badge bg-{% if prompt.model == 'haiku' %}success{% elif prompt.model == 'opus' %}danger{% else %}primary{% endif %}">
                                            {{ prompt.model|title }}
                                        </span>
                                    </td>
                                    <td>
                                        <small class="text-muted">
                                            {% if prompt.persona == 'basic_agent' %}Basic
                                            {% elif prompt.persona == 'deep_research_agent' %}Research  
                                            {% elif prompt.persona == 'autonomous_engineer' %}Engineer
                                            {% else %}{{ prompt.persona }}{% endif %}
                                        </small>
                                    </td>
                                    <td>{{ prompt.created_at.strftime('%Y-%m-%d %H:%M') }}</td>
                                    <td>
                                        <div class="btn-group" role="group">
                                            <button class="btn btn-sm btn-outline-primary" onclick="viewPrompt('{{ prompt.id }}')" title="View">
                                                <i class="fas fa-eye"></i>
                                            </button>
                                            <button class="btn btn-sm btn-outline-warning" onclick="editPrompt('{{ prompt.id }}')" title="Edit">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button class="btn btn-sm btn-outline-success" onclick="executePrompt('{{ prompt.id }}', '{{ prompt.name }}')" id="exec-btn-{{ prompt.id }}" title="Execute">
                                                <i class="fas fa-play"></i>
                                            </button>
                                            <button class="btn btn-sm btn-outline-info" onclick="viewPromptHistory('{{ prompt.id }}', '{{ prompt.name }}')" title="View History">
                                                <i class="fas fa-history"></i>
                                            </button>
                                            <button class="btn btn-sm btn-outline-danger" onclick="deletePrompt('{{ prompt.id }}')" title="Delete">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                {% else %}
                    <div class="text-center text-muted py-4">
                        <i class="fas fa-inbox me-2"></i>No prompts created yet. 
                        <button class="btn btn-link p-0" onclick="showCreateForm()">Create your first prompt</button>.
                    </div>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<!-- Modal for viewing prompt -->
<div class="modal fade" id="promptModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="promptModalTitle">Prompt Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row mb-3">
                    <div class="col-md-6">
                        <strong>Name:</strong>
                        <p id="viewPromptName" class="mb-1"></p>
                    </div>
                    <div class="col-md-6">
                        <strong>Description:</strong>
                        <p id="viewPromptDescription" class="mb-1"></p>
                    </div>
                </div>
                <div class="row mb-3">
                    <div class="col-md-6">
                        <strong>Model:</strong>
                        <span id="viewPromptModel" class="badge"></span>
                    </div>
                    <div class="col-md-6">
                        <strong>Persona:</strong>
                        <span id="viewPromptPersona" class="text-muted"></span>
                    </div>
                </div>
                <div class="mb-3">
                    <strong>Prompt Text:</strong>
                    <pre id="viewPromptText" class="bg-light p-3 mt-2"></pre>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-warning" onclick="editPromptFromView()">
                    <i class="fas fa-edit me-2"></i>Edit
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Modal for editing prompt -->
<div class="modal fade" id="editPromptModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editPromptModalTitle">Edit Prompt</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="editPromptForm">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="editPromptName" class="form-label">Name</label>
                                <input type="text" class="form-control" id="editPromptName" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="editPromptDescription" class="form-label">Description</label>
                                <input type="text" class="form-control" id="editPromptDescription">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="editPromptModel" class="form-label">AI Model</label>
                                <select class="form-control" id="editPromptModel" required>
                                    <option value="haiku">Haiku (Fast)</option>
                                    <option value="sonnet">Sonnet (Balanced)</option>
                                    <option value="sonnet-3.5">Sonnet 3.5 (Advanced)</option>
                                    <option value="opus">Opus (Most Powerful)</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="editPromptPersona" class="form-label">Agent Persona</label>
                                <select class="form-control" id="editPromptPersona" required>
                                    <option value="basic_agent">Basic Agent</option>
                                    <option value="deep_research_agent">Deep Research Agent</option>
                                    <option value="autonomous_engineer">Autonomous Engineer</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="editPromptText" class="form-label">Prompt Text</label>
                        <textarea class="form-control" id="editPromptText" rows="6" required></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-success" onclick="savePrompt()">
                    <i class="fas fa-save me-2"></i>Save Changes
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Modal for execution results -->
<div class="modal fade" id="executionModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="executionModalTitle">Execution Results</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="executionStatus" class="mb-3"></div>
                <div id="executionOutput" class="bg-light p-3" style="display: none;">
                    <pre id="executionOutputContent"></pre>
                </div>
                <div id="executionError" class="bg-danger-subtle p-3 text-danger" style="display: none;">
                    <strong>Error:</strong>
                    <pre id="executionErrorContent"></pre>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="promptViewSessionButton" onclick="viewPromptSession()" style="display: none;">
                    <i class="fas fa-comments me-2"></i>View Session
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Modal for prompt execution history -->
<div class="modal fade" id="promptHistoryModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="promptHistoryTitle">Prompt Execution History</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="promptHistoryLoading" class="text-center">
                    <i class="fas fa-spinner fa-spin me-2"></i>Loading execution history...
                </div>
                <div id="promptHistoryContent" style="display: none;">
                    <div class="table-responsive">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>Started</th>
                                    <th>Job</th>
                                    <th>Duration</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="promptHistoryTableBody">
                            </tbody>
                        </table>
                    </div>
                    <div id="promptHistoryEmpty" class="text-center text-muted" style="display: none;">
                        <i class="fas fa-inbox me-2"></i>No executions found for this prompt.
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
let currentPromptId = null;
let currentPromptSessionId = null;

// Handle create form visibility
function showCreateForm() {
    document.getElementById('createForm').style.display = 'block';
    document.getElementById('showCreateFormBtn').style.display = 'none';
    document.getElementById('name').focus();
}

function hideCreateForm() {
    document.getElementById('createForm').style.display = 'none';
    document.getElementById('showCreateFormBtn').style.display = 'inline-block';
}

// Check if we should show create form on load
document.addEventListener('DOMContentLoaded', function() {
    if (window.location.hash === '#create') {
        showCreateForm();
    }
});

function viewPrompt(id) {
    fetch(`/api/prompts/${id}`)
        .then(response => response.json())
        .then(data => {
            document.getElementById('promptModalTitle').textContent = 'Prompt: ' + data.name;
            document.getElementById('viewPromptName').textContent = data.name;
            document.getElementById('viewPromptDescription').textContent = data.description || '-';
            document.getElementById('viewPromptText').textContent = data.prompt_text;
            
            // Set model badge with color
            const modelBadge = document.getElementById('viewPromptModel');
            modelBadge.textContent = data.model.charAt(0).toUpperCase() + data.model.slice(1);
            modelBadge.className = `badge bg-${data.model === 'haiku' ? 'success' : data.model === 'opus' ? 'danger' : 'primary'}`;
            
            // Set persona text
            const personaMap = {
                'basic_agent': 'Basic Agent',
                'deep_research_agent': 'Deep Research Agent', 
                'autonomous_engineer': 'Autonomous Engineer'
            };
            document.getElementById('viewPromptPersona').textContent = personaMap[data.persona] || data.persona;
            
            currentPromptId = id;
            new bootstrap.Modal(document.getElementById('promptModal')).show();
        })
        .catch(error => {
            alert('Error loading prompt details: ' + error);
        });
}

function editPrompt(id) {
    fetch(`/api/prompts/${id}`)
        .then(response => response.json())
        .then(data => {
            // Populate edit form
            document.getElementById('editPromptName').value = data.name;
            document.getElementById('editPromptDescription').value = data.description || '';
            document.getElementById('editPromptModel').value = data.model;
            document.getElementById('editPromptPersona').value = data.persona;
            document.getElementById('editPromptText').value = data.prompt_text;
            
            document.getElementById('editPromptModalTitle').textContent = 'Edit: ' + data.name;
            currentPromptId = id;
            new bootstrap.Modal(document.getElementById('editPromptModal')).show();
        })
        .catch(error => {
            alert('Error loading prompt for editing: ' + error);
        });
}

function editPromptFromView() {
    // Close view modal and open edit modal
    bootstrap.Modal.getInstance(document.getElementById('promptModal')).hide();
    setTimeout(() => editPrompt(currentPromptId), 300);
}

function savePrompt() {
    if (!currentPromptId) return;
    
    const data = {
        name: document.getElementById('editPromptName').value,
        description: document.getElementById('editPromptDescription').value,
        model: document.getElementById('editPromptModel').value,
        persona: document.getElementById('editPromptPersona').value,
        prompt_text: document.getElementById('editPromptText').value
    };
    
    fetch(`/api/prompts/${currentPromptId}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(result => {
        bootstrap.Modal.getInstance(document.getElementById('editPromptModal')).hide();
        location.reload(); // Refresh to show updated data
    })
    .catch(error => {
        alert('Error saving prompt: ' + error);
    });
}

function deletePrompt(id) {
    if (confirm('Are you sure you want to delete this prompt?')) {
        fetch(`/api/prompts/${id}`, { method: 'DELETE' })
            .then(() => location.reload())
            .catch(error => alert('Error deleting prompt: ' + error));
    }
}

function executePrompt(id, name) {
    const button = document.getElementById(`exec-btn-${id}`);
    const originalHtml = button.innerHTML;
    
    // Show loading state
    button.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
    button.disabled = true;
    
    // Execute the prompt
    fetch(`/api/prompts/${id}/execute`, { 
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.execution_id) {
            showExecutionModal(id, data.execution_id, name);
        } else {
            alert('Error starting execution: ' + (data.detail || 'Unknown error'));
        }
    })
    .catch(error => {
        alert('Error executing prompt: ' + error);
    })
    .finally(() => {
        // Restore button state
        button.innerHTML = originalHtml;
        button.disabled = false;
    });
}

function showExecutionModal(promptId, executionId, promptName) {
    document.getElementById('executionModalTitle').textContent = `Executing: ${promptName}`;
    document.getElementById('executionStatus').innerHTML = 
        '<div class="alert alert-info"><i class="fas fa-spinner fa-spin me-2"></i>Executing prompt...</div>';
    document.getElementById('executionOutput').style.display = 'none';
    document.getElementById('executionError').style.display = 'none';
    
    const modal = new bootstrap.Modal(document.getElementById('executionModal'));
    modal.show();
    
    // Poll for execution status
    pollExecutionStatus(promptId, executionId);
}

function pollExecutionStatus(promptId, executionId) {
    const pollInterval = setInterval(() => {
        fetch(`/api/prompts/${promptId}/executions/${executionId}`)
            .then(response => response.json())
            .then(data => {
                const statusDiv = document.getElementById('executionStatus');
                const outputDiv = document.getElementById('executionOutput');
                const errorDiv = document.getElementById('executionError');
                
                if (data.status === 'running') {
                    statusDiv.innerHTML = 
                        '<div class="alert alert-info"><i class="fas fa-spinner fa-spin me-2"></i>Executing prompt...</div>';
                } else if (data.status === 'completed') {
                    clearInterval(pollInterval);
                    statusDiv.innerHTML = 
                        '<div class="alert alert-success"><i class="fas fa-check me-2"></i>Execution completed successfully!</div>';
                    
                    // Store session ID and show session button if available
                    currentPromptSessionId = data.session_id;
                    const sessionButton = document.getElementById('promptViewSessionButton');
                    if (currentPromptSessionId) {
                        sessionButton.style.display = 'inline-block';
                    }
                    
                    if (data.output) {
                        outputDiv.style.display = 'block';
                        document.getElementById('executionOutputContent').textContent = data.output;
                    }
                } else if (data.status === 'failed') {
                    clearInterval(pollInterval);
                    statusDiv.innerHTML = 
                        '<div class="alert alert-danger"><i class="fas fa-times me-2"></i>Execution failed</div>';
                    
                    if (data.error_message) {
                        errorDiv.style.display = 'block';
                        document.getElementById('executionErrorContent').textContent = data.error_message;
                    }
                }
            })
            .catch(error => {
                clearInterval(pollInterval);
                console.error('Error polling execution status:', error);
                document.getElementById('executionStatus').innerHTML = 
                    '<div class="alert alert-danger"><i class="fas fa-times me-2"></i>Error checking execution status</div>';
            });
    }, 2000); // Poll every 2 seconds
    
    // Stop polling after 10 minutes to avoid infinite polling
    setTimeout(() => {
        clearInterval(pollInterval);
    }, 600000);
}

function viewPromptSession() {
    if (currentPromptSessionId) {
        // Open session history in new tab
        window.open(`/sessions/${currentPromptSessionId}`, '_blank');
    } else {
        alert('No session ID available for this execution');
    }
}

function viewPromptHistory(promptId, promptName) {
    // Set modal title and show loading
    document.getElementById('promptHistoryTitle').textContent = `Execution History: ${promptName}`;
    document.getElementById('promptHistoryLoading').style.display = 'block';
    document.getElementById('promptHistoryContent').style.display = 'none';
    
    // Show the modal
    const modal = new bootstrap.Modal(document.getElementById('promptHistoryModal'));
    modal.show();
    
    // Fetch execution history
    fetch(`/api/prompts/${promptId}/executions`)
        .then(response => response.json())
        .then(executions => {
            document.getElementById('promptHistoryLoading').style.display = 'none';
            document.getElementById('promptHistoryContent').style.display = 'block';
            
            const tbody = document.getElementById('promptHistoryTableBody');
            tbody.innerHTML = '';
            
            if (executions.length === 0) {
                document.getElementById('promptHistoryEmpty').style.display = 'block';
                return;
            }
            
            executions.forEach(execution => {
                const row = document.createElement('tr');
                
                // Format timestamps
                const startedAt = new Date(execution.started_at).toLocaleString();
                
                // Calculate duration
                let duration = '-';
                if (execution.completed_at) {
                    const start = new Date(execution.started_at);
                    const end = new Date(execution.completed_at);
                    const diffSeconds = Math.floor((end - start) / 1000);
                    if (diffSeconds < 60) {
                        duration = `${diffSeconds}s`;
                    } else {
                        duration = `${Math.floor(diffSeconds / 60)}m ${diffSeconds % 60}s`;
                    }
                } else if (execution.status === 'running') {
                    duration = 'Running...';
                }
                
                // Status badge
                let statusBadge = '';
                if (execution.status === 'completed') {
                    statusBadge = '<span class="badge bg-success">Completed</span>';
                } else if (execution.status === 'failed') {
                    statusBadge = '<span class="badge bg-danger">Failed</span>';
                } else if (execution.status === 'running') {
                    statusBadge = '<span class="badge bg-primary">Running</span>';
                } else {
                    statusBadge = `<span class="badge bg-secondary">${execution.status}</span>`;
                }
                
                // Actions
                const actions = (execution.session_id) ? 
                    `<button class="btn btn-sm btn-outline-primary" onclick="window.open('/sessions/${execution.session_id}', '_blank')" title="View Session">
                        <i class="fas fa-comments"></i>
                    </button>` : '-';
                
                row.innerHTML = `
                    <td>${startedAt}</td>
                    <td>${execution.job_name || '<em class="text-muted">Manual</em>'}</td>
                    <td>${duration}</td>
                    <td>${statusBadge}</td>
                    <td>${actions}</td>
                `;
                
                tbody.appendChild(row);
            });
        })
        .catch(error => {
            document.getElementById('promptHistoryLoading').style.display = 'none';
            document.getElementById('promptHistoryContent').innerHTML = 
                '<div class="alert alert-danger">Error loading execution history: ' + error + '</div>';
            document.getElementById('promptHistoryContent').style.display = 'block';
        });
}
</script>
{% endblock %}