{% extends "base.html" %}

{% block title %}Specialist Execution Status{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h4>Specialist Execution Status</h4>
                    {% if specialist %}
                    <span class="badge bg-primary">{{ specialist.name }}</span>
                    {% endif %}
                </div>
                <div class="card-body">
                    <div class="progress mb-4">
                        <div id="progress-bar" class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%"></div>
                    </div>

                    <div class="mb-4">
                        <h5>Current Status:</h5>
                        <div id="current-status" class="alert alert-info">Execution starting...</div>
                    </div>

                    <div class="mb-4">
                        <h5>Execution Log:</h5>
                        <div id="execution-log" class="border p-3 bg-light" style="max-height: 300px; overflow-y: auto;">
                            <div class="text-muted">Waiting for updates...</div>
                        </div>
                    </div>

                    <div id="completion-actions" class="d-none">
                        <hr>
                        <h5>Execution Completed</h5>
                        <p>The specialist has completed processing.</p>
                        <a id="view-results-btn" href="{{ prefixed_url_for('interaction_bp.view_chat_session_by_session_id', session_id=chat_session_id) }}" class="btn btn-primary">View Results</a>
                        <a href="{{ prefixed_url_for('interaction_bp.specialists') }}" class="btn btn-secondary">Back to Specialists</a>
                    </div>

                    <div id="error-actions" class="d-none">
                        <hr>
                        <h5>Error Occurred</h5>
                        <p>An error occurred during specialist execution.</p>
                        <div id="error-details" class="alert alert-danger"></div>
                        <a href="{{ prefixed_url_for('interaction_bp.specialists') }}" class="btn btn-secondary">Back to Specialists</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const taskId = "{{ task_id }}";
        const executionLog = document.getElementById('execution-log');
        const currentStatus = document.getElementById('current-status');
        const progressBar = document.getElementById('progress-bar');
        const completionActions = document.getElementById('completion-actions');
        const errorActions = document.getElementById('error-actions');
        const errorDetails = document.getElementById('error-details');

        let logEntries = [];
        let isComplete = false;

        // Connect to the SSE stream
        const eventSource = new EventSource("{{ prefixed_url_for('interaction_bp.specialist_execution_updates', task_id=task_id) }}");

        // General data handler
        eventSource.onmessage = function(event) {
            const data = JSON.parse(event.data);
            addLogEntry(data);
            updateStatus(data);
        };

        // Specific event handlers
        eventSource.addEventListener('Task Started', function(event) {
            const data = JSON.parse(event.data);
            progressBar.style.width = '10%';
            currentStatus.textContent = 'Task started: ' + data.data.message;
            currentStatus.className = 'alert alert-info';
        });

        eventSource.addEventListener('Task Progress', function(event) {
            const data = JSON.parse(event.data);
            // Update progress percentage if available
            if (data.data.percentage) {
                progressBar.style.width = data.data.percentage + '%';
            } else {
                // Incremental progress if no percentage available
                const currentWidth = parseInt(progressBar.style.width) || 0;
                progressBar.style.width = Math.min(currentWidth + 5, 90) + '%';
            }
        });

        eventSource.addEventListener('Task Complete', function(event) {
            const data = JSON.parse(event.data);
            progressBar.style.width = '100%';
            progressBar.className = 'progress-bar bg-success';
            currentStatus.textContent = 'Processing completed: ' + data.data.message;
            currentStatus.className = 'alert alert-success';
            completionActions.classList.remove('d-none');
            isComplete = true;
            eventSource.close();
        });

        eventSource.addEventListener('Task Error', function(event) {
            const data = JSON.parse(event.data);
            progressBar.className = 'progress-bar bg-danger';
            currentStatus.textContent = 'Error occurred';
            currentStatus.className = 'alert alert-danger';
            errorDetails.textContent = data.data.error;
            errorActions.classList.remove('d-none');
            eventSource.close();
        });

        eventSource.addEventListener('EveAI Specialist Complete', function(event) {
            const data = JSON.parse(event.data);
            progressBar.style.width = '100%';
            progressBar.className = 'progress-bar bg-success';
            currentStatus.textContent = 'Specialist processing completed';
            currentStatus.className = 'alert alert-success';
            completionActions.classList.remove('d-none');
            isComplete = true;
            eventSource.close();
        });

        eventSource.onerror = function(event) {
            // Only report an error if the task is not already completed
            if (!isComplete) {
                currentStatus.textContent = 'Connection to server lost';
                currentStatus.className = 'alert alert-warning';
                errorDetails.textContent = 'The connection to the server was lost. The task may still be running.';
                errorActions.classList.remove('d-none');
            }
        };

        function addLogEntry(data) {
            const timestamp = new Date(data.timestamp).toLocaleTimeString();
            const message = data.data.message || JSON.stringify(data.data);
            const type = data.processing_type;

            // Add the log entry to the array
            logEntries.push({timestamp, message, type});

            // Limit to last 100 entries
            if (logEntries.length > 100) {
                logEntries.shift();
            }

            // Refresh the log element
            renderLog();
        }

        function renderLog() {
            executionLog.innerHTML = '';

            logEntries.forEach(entry => {
                const entryElement = document.createElement('div');
                entryElement.className = 'log-entry mb-1';

                // Determine the appropriate badge color based on type
                let badgeClass = 'bg-secondary';
                if (entry.type === 'Task Started') badgeClass = 'bg-primary';
                if (entry.type === 'Task Progress') badgeClass = 'bg-info';
                if (entry.type === 'Task Complete' || entry.type === 'EveAI Specialist Complete') badgeClass = 'bg-success';
                if (entry.type === 'Task Error') badgeClass = 'bg-danger';

                entryElement.innerHTML = `
                    <span class="badge ${badgeClass}">${entry.timestamp}</span>
                    <span class="ms-2">${entry.message}</span>
                `;

                executionLog.appendChild(entryElement);
            });

            // Scroll to bottom
            executionLog.scrollTop = executionLog.scrollHeight;
        }

        function updateStatus(data) {
            // Update the current status with the latest information
            if (data.data.message) {
                currentStatus.textContent = data.data.message;
            }
        }
    });
</script>
{% endblock %}