{% extends "base.jinja2" %}

{% block title %}Messages - VibeX Observability{% endblock %}

{% block content %}
<!-- Page Header -->
<div class="sm:flex sm:justify-between sm:items-center mb-8">
    <div class="mb-4 sm:mb-0">
        <h1 class="text-2xl font-semibold text-gray-800 dark:text-neutral-200">Messages</h1>
        <p class="text-sm text-gray-600 dark:text-neutral-400">Agent conversation history and task execution logs</p>
    </div>

    <div class="flex gap-x-2">
        <button
            type="button"
            class="py-2 px-3 inline-flex items-center gap-x-2 text-sm font-medium rounded-lg border border-gray-200 bg-white text-gray-800 shadow-sm hover:bg-gray-50 focus:outline-none focus:bg-gray-50 disabled:opacity-50 disabled:pointer-events-none dark:bg-neutral-800 dark:border-neutral-700 dark:text-white dark:hover:bg-neutral-700 dark:focus:bg-neutral-700"
            onclick="window.location.reload()"
        >
            <i data-lucide="refresh-cw" class="shrink-0 size-4"></i>
            Refresh
        </button>

        <button
            type="button"
            class="py-2 px-3 inline-flex items-center gap-x-2 text-sm font-medium rounded-lg border border-transparent bg-blue-600 text-white hover:bg-blue-700 focus:outline-none focus:bg-blue-700 disabled:opacity-50 disabled:pointer-events-none"
            onclick="exportMessagesHistory()"
        >
            <i data-lucide="download" class="shrink-0 size-4"></i>
            Export
        </button>
    </div>
</div>

<!-- Messages Interface -->
<div class="grid lg:grid-cols-4 gap-6">
    <!-- Task List Sidebar -->
    <div class="lg:col-span-1">
        <div class="flex flex-col bg-white border shadow-sm rounded-xl dark:bg-neutral-800 dark:border-neutral-700 h-[calc(100vh-200px)]">
            <div class="px-4 py-3 border-b border-gray-200 dark:border-neutral-700">
                <h3 class="text-lg font-semibold text-gray-800 dark:text-neutral-200">Tasks</h3>
                <p class="text-xs text-gray-600 dark:text-neutral-400">Select a task to view conversation</p>
            </div>

            <div class="flex-1 overflow-y-auto custom-scrollbar">
                {% if all_tasks %}
                    <div class="p-2 space-y-1">
                        {% for task_id in all_tasks %}
                        <button
                            type="button"
                            class="task-item w-full text-left p-3 rounded-lg hover:bg-gray-50 dark:hover:bg-neutral-700 transition-colors"
                            data-task-id="{{ task_id }}"
                            onclick="loadTaskConversation('{{ task_id }}')"
                        >
                            <div class="flex items-center justify-between">
                                <span class="text-sm font-mono text-gray-800 dark:text-neutral-200 truncate">{{ task_id }}</span>
                                <i data-lucide="chevron-right" class="shrink-0 size-4 text-gray-400"></i>
                            </div>
                        </button>
                        {% endfor %}
                    </div>
                {% else %}
                    <div class="flex flex-col items-center justify-center h-full p-4">
                        <i data-lucide="inbox" class="size-12 text-gray-400 dark:text-neutral-500 mb-3"></i>
                        <p class="text-sm text-gray-600 dark:text-neutral-400 text-center">No tasks found</p>
                        <p class="text-xs text-gray-500 dark:text-neutral-500 text-center">Tasks will appear here after running VibeX</p>
                    </div>
                {% endif %}
            </div>
        </div>
    </div>

    <!-- Message Display -->
    <div class="lg:col-span-3">
        <div class="flex flex-col bg-white border shadow-sm rounded-xl dark:bg-neutral-800 dark:border-neutral-700 h-[calc(100vh-200px)]">
            <!-- Messages Header -->
            <div class="px-6 py-4 border-b border-gray-200 dark:border-neutral-700">
                <div class="flex items-center justify-between">
                    <div>
                        <h3 id="messages-task-title" class="text-lg font-semibold text-gray-800 dark:text-neutral-200">Select a Task</h3>
                        <p id="messages-task-subtitle" class="text-sm text-gray-600 dark:text-neutral-400">Choose a task from the sidebar to view conversation history</p>
                    </div>

                    <div class="flex items-center gap-x-2">
                        <!-- Message Type Filter -->
                        <select id="message-filter" class="py-1.5 px-3 pe-9 block border-gray-200 rounded-lg text-sm focus:border-blue-500 focus:ring-blue-500 disabled:opacity-50 disabled:pointer-events-none dark:bg-neutral-800 dark:border-neutral-700 dark:text-neutral-400 dark:placeholder:text-neutral-400 dark:focus:ring-neutral-600" onchange="filterMessages()">
                            <option value="all">All Messages</option>
                            <option value="message">Messages Only</option>
                            <option value="tool">Tool Calls</option>
                            <option value="error">Errors Only</option>
                        </select>

                        <!-- Auto-scroll toggle -->
                        <button
                            type="button"
                            id="auto-scroll-toggle"
                            class="py-1.5 px-3 inline-flex items-center gap-x-2 text-sm font-medium rounded-lg border border-gray-200 bg-white text-gray-800 shadow-sm hover:bg-gray-50 focus:outline-none focus:bg-gray-50 disabled:opacity-50 disabled:pointer-events-none dark:bg-neutral-800 dark:border-neutral-700 dark:text-white dark:hover:bg-neutral-700 dark:focus:bg-neutral-700"
                            onclick="toggleAutoScroll()"
                        >
                            <i data-lucide="arrow-down" class="shrink-0 size-4"></i>
                            Auto-scroll
                        </button>
                    </div>
                </div>
            </div>

            <!-- Messages Container -->
            <div id="messages-container" class="flex-1 overflow-y-auto custom-scrollbar p-6">
                <div id="welcome-message" class="flex flex-col items-center justify-center h-full">
                    <i data-lucide="message-circle" class="size-16 text-gray-400 dark:text-neutral-500 mb-4"></i>
                    <h3 class="text-lg font-semibold text-gray-800 dark:text-neutral-200 mb-2">Welcome to Messages</h3>
                    <p class="text-sm text-gray-600 dark:text-neutral-400 text-center max-w-md">
                        This is where you can view the conversation history between agents during task execution.
                        Select a task from the sidebar to see the detailed agent interactions.
                    </p>
                </div>

                <!-- Messages will be loaded here -->
                <div id="conversation-messages" class="space-y-4 hidden"></div>
            </div>

            <!-- Messages Footer -->
            <div id="messages-footer" class="px-6 py-3 border-t border-gray-200 dark:border-neutral-700 hidden">
                <div class="flex items-center justify-between text-sm text-gray-600 dark:text-neutral-400">
                    <span id="message-count">0 messages</span>
                    <span id="conversation-time">No conversation loaded</span>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
let currentTaskId = null;
let allMessages = [];
let autoScroll = true;

// Load conversation for a specific task
async function loadTaskConversation(taskId) {
    currentTaskId = taskId;

    // Update UI
    document.getElementById('messages-task-title').textContent = `Task: ${taskId}`;
    document.getElementById('messages-task-subtitle').textContent = 'Loading conversation...';

    // Highlight selected task
    document.querySelectorAll('.task-item').forEach(item => {
        item.classList.remove('bg-blue-50', 'dark:bg-blue-900/20', 'border-blue-200', 'dark:border-blue-800');
    });
    document.querySelector(`[data-task-id="${taskId}"]`).classList.add('bg-blue-50', 'dark:bg-blue-900/20', 'border', 'border-blue-200', 'dark:border-blue-800');

    // Hide welcome message
    document.getElementById('welcome-message').classList.add('hidden');
    document.getElementById('conversation-messages').classList.remove('hidden');
    document.getElementById('messages-footer').classList.remove('hidden');

    try {
        const response = await fetch(`/api/task/${taskId}/conversation`);
        const data = await response.json();

        if (data.conversation && data.conversation.length > 0) {
            allMessages = data.conversation;
            displayMessages(allMessages);

            // Update footer
            document.getElementById('message-count').textContent = `${allMessages.length} messages`;
            document.getElementById('messages-task-subtitle').textContent = `${allMessages.length} messages in conversation`;

            if (allMessages.length > 0) {
                const firstMessage = new Date(allMessages[0].timestamp);
                const lastMessage = new Date(allMessages[allMessages.length - 1].timestamp);
                document.getElementById('conversation-time').textContent =
                    `${firstMessage.toLocaleString()} - ${lastMessage.toLocaleString()}`;
            }
        } else {
            // No conversation found
            document.getElementById('conversation-messages').innerHTML = `
                <div class="text-center py-8">
                    <i data-lucide="message-square-x" class="mx-auto size-12 text-gray-400 dark:text-neutral-500 mb-3"></i>
                    <p class="text-sm text-gray-600 dark:text-neutral-400">No conversation history found for this task</p>
                </div>
            `;
            lucide.createIcons();

            document.getElementById('message-count').textContent = '0 messages';
            document.getElementById('conversation-time').textContent = 'No conversation data';
            document.getElementById('messages-task-subtitle').textContent = 'No conversation history available';
        }
    } catch (error) {
        console.error('Failed to load conversation:', error);
        document.getElementById('conversation-messages').innerHTML = `
            <div class="text-center py-8">
                <i data-lucide="alert-circle" class="mx-auto size-12 text-red-400 mb-3"></i>
                <p class="text-sm text-red-600 dark:text-red-400">Failed to load conversation: ${error.message}</p>
            </div>
        `;
        lucide.createIcons();
    }
}

// Display messages in the interface
function displayMessages(messages) {
    const container = document.getElementById('conversation-messages');
    container.innerHTML = '';

    messages.forEach((message, index) => {
        const messageEl = createMessageElement(message, index);
        container.appendChild(messageEl);
    });

    // Re-initialize Lucide icons
    lucide.createIcons();

    // Auto-scroll to bottom
    if (autoScroll) {
        scrollToBottom();
    }
}

// Create a message element
function createMessageElement(message, index) {
    const messageDiv = document.createElement('div');
    messageDiv.className = `message-item message-type-${message.type}`;

    const time = new Date(message.timestamp).toLocaleTimeString();
    const messageTypeIcon = getMessageTypeIcon(message.type);
    const messageTypeColor = getMessageTypeColor(message.type);

    messageDiv.innerHTML = `
        <div class="flex gap-x-3">
            <div class="shrink-0">
                <div class="size-8 rounded-full ${messageTypeColor} flex items-center justify-center">
                    <i data-lucide="${messageTypeIcon}" class="size-4 text-white"></i>
                </div>
            </div>

            <div class="flex-1 min-w-0">
                <div class="flex items-center gap-x-2 mb-1">
                    <span class="text-sm font-semibold text-gray-800 dark:text-neutral-200">${message.agent}</span>
                    <span class="text-xs text-gray-500 dark:text-neutral-500">${time}</span>
                    <span class="inline-flex items-center py-0.5 px-1.5 rounded-full text-xs font-medium ${getMessageTypeBadgeColor(message.type)}">${message.type}</span>
                </div>

                <div class="text-sm text-gray-700 dark:text-neutral-300 whitespace-pre-wrap break-words">
                    ${escapeHtml(message.message)}
                </div>
            </div>
        </div>
    `;

    return messageDiv;
}

// Get icon for message type
function getMessageTypeIcon(type) {
    switch (type) {
        case 'tool': return 'wrench';
        case 'error': return 'x-circle';
        case 'system': return 'settings';
        default: return 'message-circle';
    }
}

// Get color for message type
function getMessageTypeColor(type) {
    switch (type) {
        case 'tool': return 'bg-blue-600';
        case 'error': return 'bg-red-600';
        case 'system': return 'bg-gray-600';
        default: return 'bg-green-600';
    }
}

// Get badge color for message type
function getMessageTypeBadgeColor(type) {
    switch (type) {
        case 'tool': return 'bg-blue-100 text-blue-800 dark:bg-blue-800/30 dark:text-blue-500';
        case 'error': return 'bg-red-100 text-red-800 dark:bg-red-800/30 dark:text-red-500';
        case 'system': return 'bg-gray-100 text-gray-800 dark:bg-neutral-700 dark:text-neutral-200';
        default: return 'bg-green-100 text-green-800 dark:bg-green-800/30 dark:text-green-500';
    }
}

// Filter messages by type
function filterMessages() {
    const filterValue = document.getElementById('message-filter').value;

    if (filterValue === 'all') {
        displayMessages(allMessages);
    } else {
        const filteredMessages = allMessages.filter(msg => msg.type === filterValue);
        displayMessages(filteredMessages);
    }
}

// Toggle auto-scroll
function toggleAutoScroll() {
    autoScroll = !autoScroll;
    const button = document.getElementById('auto-scroll-toggle');

    if (autoScroll) {
        button.classList.add('bg-blue-50', 'text-blue-600', 'border-blue-200');
        button.classList.remove('bg-white', 'text-gray-800', 'border-gray-200');
        scrollToBottom();
    } else {
        button.classList.remove('bg-blue-50', 'text-blue-600', 'border-blue-200');
        button.classList.add('bg-white', 'text-gray-800', 'border-gray-200');
    }
}

// Scroll to bottom of messages
function scrollToBottom() {
    const messagesContainer = document.getElementById('messages-container');
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
}

// Export messages history
function exportMessagesHistory() {
    if (!currentTaskId || !allMessages.length) {
        alert('No conversation to export. Please select a task first.');
        return;
    }

    const exportData = {
        task_id: currentTaskId,
        exported_at: new Date().toISOString(),
        message_count: allMessages.length,
        conversation: allMessages
    };

    const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `vibex-messages-${currentTaskId}-${new Date().toISOString().split('T')[0]}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
}

// Escape HTML to prevent XSS
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// Auto-load first task if available
document.addEventListener('DOMContentLoaded', function() {
    const firstTask = document.querySelector('.task-item');
    if (firstTask) {
        const taskId = firstTask.getAttribute('data-task-id');
        loadTaskConversation(taskId);
    }
});
</script>
{% endblock %}
