// Chat Main - AI Chat frontend with multi-session support
// Sessions are persisted server-side via AiChatSession / AiChatMessage

let sessions = [];
let currentSessionId = null;
let chatMessages = [];
let isWaiting = false;
let showingArchived = false;

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

// ---- Sidebar ----

async function loadSessions() {
    const archived = showingArchived ? 1 : 0;
    sessions = await AiChatSession.list(archived);
    renderSidebar();
}

function renderSidebar() {
    const container = document.getElementById('sessionList');
    if (sessions.length === 0) {
        container.innerHTML = `<div class="sidebar-empty">${showingArchived ? 'No archived chats' : 'No chats yet'}</div>`;
        return;
    }

    let html = '';
    for (const s of sessions) {
        const isActive = s.id === currentSessionId;
        const date = s.last_message_at ? new Date(s.last_message_at * 1000).toLocaleDateString() : '';
        const msgCount = s.message_count || 0;
        html += `<div class="session-item${isActive ? ' active' : ''}" onclick="switchToSession(${s.id})">
            <div class="session-title">${escapeHtml(s.title || 'New Chat')}</div>
            <div class="session-meta">${msgCount} msg${msgCount !== 1 ? 's' : ''} &middot; ${date}</div>
            <div class="session-actions">
                <button onclick="event.stopPropagation(); renameSession(${s.id})" title="Rename">R</button>
                <button onclick="event.stopPropagation(); archiveSession(${s.id})" title="${showingArchived ? 'Unarchive' : 'Archive'}">A</button>
                <button onclick="event.stopPropagation(); deleteSession(${s.id})" title="Delete">X</button>
            </div>
        </div>`;
    }
    container.innerHTML = html;
}

async function createNewSession() {
    const session = await AiChatSession.create();
    currentSessionId = session.id;
    chatMessages = [];
    await loadSessions();
    renderMessages();
}

async function switchToSession(id) {
    if (id === currentSessionId) return;
    currentSessionId = id;

    const session = sessions.find(s => s.id === id);
    if (!session) return;

    const rawMessages = await session.loadMessages();

    // Convert server messages to the format renderMessages expects
    chatMessages = rawMessages.map(m => {
        const msg = { role: m.role, content: m.content };
        if (m.role === 'assistant') {
            msg.sql = m.sql || '';
            msg.error = m.error || '';
            msg.row_count = m.row_count || 0;
            // Parse JSON fields
            try { msg.columns = JSON.parse(m.columns_json || '[]'); } catch { msg.columns = []; }
            try { msg.results = JSON.parse(m.results_json || '[]'); } catch { msg.results = []; }
            // Parse multi-step queries
            try {
                const q = JSON.parse(m.queries_json || '[]');
                if (Array.isArray(q) && q.length > 0) {
                    // Parse nested columns/results if they're strings
                    msg.queries = q.map(step => ({
                        sql: step.sql || '',
                        columns: Array.isArray(step.columns) ? step.columns : [],
                        results: Array.isArray(step.results) ? step.results : [],
                        row_count: step.row_count || 0,
                        error: step.error || ''
                    }));
                }
            } catch { /* no queries */ }
        }
        return msg;
    });

    renderSidebar();
    renderMessages();
}

async function renameSession(id) {
    const session = sessions.find(s => s.id === id);
    if (!session) return;
    const newTitle = prompt('Rename chat:', session.title || '');
    if (newTitle === null || newTitle.trim() === '') return;
    await new AiChatSession({ id }).update({ title: newTitle.trim() });
    await loadSessions();
}

async function archiveSession(id) {
    const newArchived = showingArchived ? 0 : 1;
    await new AiChatSession({ id }).update({ archived: newArchived });
    if (id === currentSessionId) {
        currentSessionId = null;
        chatMessages = [];
        renderMessages();
    }
    await loadSessions();
}

async function deleteSession(id) {
    if (!confirm('Delete this chat and all its messages?')) return;
    await new AiChatSession({ id }).remove();
    if (id === currentSessionId) {
        currentSessionId = null;
        chatMessages = [];
        renderMessages();
    }
    await loadSessions();
}

function toggleArchiveView() {
    showingArchived = !showingArchived;
    const btn = document.getElementById('archiveToggleBtn');
    btn.textContent = showingArchived ? 'Active' : 'Archive';
    currentSessionId = null;
    chatMessages = [];
    renderMessages();
    loadSessions();
}

// ---- Messages ----

function renderMessages() {
    const container = document.getElementById('chatMessages');
    const welcome = document.getElementById('chatWelcome');

    if (!currentSessionId || chatMessages.length === 0) {
        welcome.style.display = 'block';
        container.innerHTML = '';
        return;
    }

    welcome.style.display = 'none';
    let html = '';

    for (const msg of chatMessages) {
        if (msg.role === 'user') {
            html += `<div class="chat-msg chat-msg-user">
                <div class="chat-bubble chat-bubble-user">${escapeHtml(msg.content)}</div>
            </div>`;
        } else if (msg.role === 'assistant') {
            html += renderAssistantMessage(msg);
        }
    }

    container.innerHTML = html;
    container.scrollTop = container.scrollHeight;
}

function renderQueryStep(step, label) {
    let html = '';
    if (step.error) {
        html += `<div class="chat-error">${escapeHtml(step.error)}</div>`;
    }
    if (step.sql) {
        html += `<details class="chat-details">
            <summary>${escapeHtml(label)} - SQL</summary>
            <pre class="chat-sql">${escapeHtml(step.sql)}</pre>
        </details>`;
    }
    if (step.columns && step.columns.length > 0 && step.row_count > 0) {
        const displayRows = step.results ? step.results.slice(0, 50) : [];
        html += `<details class="chat-details">
            <summary>${escapeHtml(label)} - Data (${step.row_count} row${step.row_count !== 1 ? 's' : ''})</summary>
            <div class="chat-table-wrap">
                <table class="chat-table">
                    <thead><tr>${step.columns.map(c => `<th>${escapeHtml(c)}</th>`).join('')}</tr></thead>
                    <tbody>`;
        for (const row of displayRows) {
            html += '<tr>' + row.map(cell => `<td>${escapeHtml(cell)}</td>`).join('') + '</tr>';
        }
        html += `</tbody></table>`;
        if (step.row_count > 50) {
            html += `<div class="chat-table-note">(showing first 50 of ${step.row_count} rows)</div>`;
        }
        html += `</div></details>`;
    }
    return html;
}

function renderAssistantMessage(msg) {
    let html = `<div class="chat-msg chat-msg-assistant"><div class="chat-bubble chat-bubble-assistant">`;

    if (msg.error) {
        html += `<div class="chat-error">${escapeHtml(msg.error)}</div>`;
    }

    if (msg.content) {
        html += `<div class="chat-text">${formatResponseText(msg.content)}</div>`;
    }

    // Multi-step queries display
    if (msg.queries && msg.queries.length > 1) {
        for (let i = 0; i < msg.queries.length; i++) {
            html += renderQueryStep(msg.queries[i], `Step ${i + 1}`);
        }
    } else if (msg.queries && msg.queries.length === 1) {
        // Single query — render inline like before
        html += renderQueryStep(msg.queries[0], 'Query');
    } else {
        // Fallback: old-style single sql/columns/results fields
        if (msg.sql) {
            html += `<details class="chat-details">
                <summary>Show SQL</summary>
                <pre class="chat-sql">${escapeHtml(msg.sql)}</pre>
            </details>`;
        }

        if (msg.columns && msg.columns.length > 0 && msg.row_count > 0) {
            const displayRows = msg.results ? msg.results.slice(0, 50) : [];
            html += `<details class="chat-details">
                <summary>Show data (${msg.row_count} row${msg.row_count !== 1 ? 's' : ''})</summary>
                <div class="chat-table-wrap">
                    <table class="chat-table">
                        <thead><tr>${msg.columns.map(c => `<th>${escapeHtml(c)}</th>`).join('')}</tr></thead>
                        <tbody>`;
            for (const row of displayRows) {
                html += '<tr>' + row.map(cell => `<td>${escapeHtml(cell)}</td>`).join('') + '</tr>';
            }
            html += `</tbody></table>`;
            if (msg.row_count > 50) {
                html += `<div class="chat-table-note">(showing first 50 of ${msg.row_count} rows)</div>`;
            }
            html += `</div></details>`;
        }
    }

    html += `</div></div>`;
    return html;
}

function formatResponseText(text) {
    let escaped = escapeHtml(text);
    escaped = escaped.replace(/\*\*(.+?)\*\*/g, '<b>$1</b>');
    escaped = escaped.replace(/`([^`]+)`/g, '<code>$1</code>');
    escaped = escaped.replace(/\n/g, '<br>');
    return escaped;
}

function showThinking() {
    const container = document.getElementById('chatMessages');
    const indicator = document.createElement('div');
    indicator.id = 'thinkingIndicator';
    indicator.className = 'chat-msg chat-msg-assistant';
    indicator.innerHTML = `<div class="chat-bubble chat-bubble-assistant chat-thinking">Thinking<span class="thinking-dots"></span></div>`;
    container.appendChild(indicator);
    container.scrollTop = container.scrollHeight;
}

function hideThinking() {
    const indicator = document.getElementById('thinkingIndicator');
    if (indicator) indicator.remove();
}

async function sendMessage(text) {
    if (!text || !text.trim() || isWaiting) return;

    const content = text.trim();

    // Auto-create session if none selected
    if (!currentSessionId) {
        const session = await AiChatSession.create();
        currentSessionId = session.id;
        await loadSessions();
    }

    chatMessages.push({ role: 'user', content });
    renderMessages();

    const input = document.getElementById('chatInput');
    input.value = '';
    input.focus();

    isWaiting = true;
    document.getElementById('chatSendBtn').disabled = true;
    showThinking();

    try {
        // Build messages array for API (only role + content)
        const apiMessages = chatMessages
            .filter(m => m.role === 'user' || m.role === 'assistant')
            .map(m => ({ role: m.role, content: m.content }));

        const res = await fetch('/api/chat', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                messages: apiMessages,
                session_id: currentSessionId
            })
        });

        const data = await res.json();

        const assistantMsg = {
            role: 'assistant',
            content: data.response || '',
            sql: data.sql || '',
            columns: data.columns || [],
            results: data.results || [],
            row_count: data.row_count || 0,
            error: data.error || ''
        };

        // Multi-step queries
        if (data.queries && Array.isArray(data.queries) && data.queries.length > 0) {
            assistantMsg.queries = data.queries;
        }

        chatMessages.push(assistantMsg);
    } catch (e) {
        chatMessages.push({
            role: 'assistant',
            content: '',
            error: 'Network error: ' + e.message,
            sql: '', columns: [], results: [], row_count: 0
        });
    } finally {
        isWaiting = false;
        document.getElementById('chatSendBtn').disabled = false;
        hideThinking();
        renderMessages();
        // Refresh sidebar to show updated message count / title
        loadSessions();
    }
}

function askExample(text) {
    document.getElementById('chatInput').value = text;
    sendMessage(text);
}

// ---- localStorage migration ----

async function migrateLocalStorage() {
    const STORAGE_KEY = 'chat_history';
    const MIGRATED_FLAG = 'chat_history_migrated';

    if (localStorage.getItem(MIGRATED_FLAG)) return;

    let oldMessages;
    try {
        const stored = localStorage.getItem(STORAGE_KEY);
        if (!stored) {
            localStorage.setItem(MIGRATED_FLAG, '1');
            return;
        }
        oldMessages = JSON.parse(stored);
        if (!Array.isArray(oldMessages) || oldMessages.length === 0) {
            localStorage.setItem(MIGRATED_FLAG, '1');
            return;
        }
    } catch {
        localStorage.setItem(MIGRATED_FLAG, '1');
        return;
    }

    try {
        // Create a session for the migrated messages
        const session = await AiChatSession.create('Migrated Chat');
        await session.importMessages(oldMessages);

        // Clean up
        localStorage.removeItem(STORAGE_KEY);
        localStorage.setItem(MIGRATED_FLAG, '1');

        console.log('Migrated', oldMessages.length, 'messages from localStorage to session', session.id);
    } catch (e) {
        console.warn('localStorage migration failed:', e);
    }
}

// ---- Init ----

async function initChat() {
    await migrateLocalStorage();
    await loadSessions();

    // Auto-select most recent session
    if (sessions.length > 0 && !currentSessionId) {
        await switchToSession(sessions[0].id);
    } else {
        renderMessages();
    }

    const input = document.getElementById('chatInput');
    input.addEventListener('keydown', (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendMessage(input.value);
        }
    });

    document.getElementById('chatSendBtn').addEventListener('click', () => {
        sendMessage(input.value);
    });

    document.getElementById('newChatBtn').addEventListener('click', () => {
        createNewSession();
    });

    document.getElementById('archiveToggleBtn').addEventListener('click', () => {
        toggleArchiveView();
    });
}
