/**
 * AI Request History tab — stats cards + paginated request log table.
 * Loaded by settings.html when the "AI Request History" tab is active.
 */

const AI_HISTORY_PAGE_SIZE = 50;
let aiHistoryOffset = 0;
let aiHistoryTotal = 0;

// ---------------------------------------------------------------------------
// Formatting helpers
// ---------------------------------------------------------------------------

function formatDuration(ms) {
    if (ms === 0) return '-';
    if (ms < 1000) return ms + 'ms';
    return (ms / 1000).toFixed(1) + 's';
}

function formatNumber(n) {
    if (n === 0) return '-';
    return n.toLocaleString();
}

function formatTime(unix) {
    if (!unix) return '-';
    const d = new Date(unix * 1000);
    const pad = v => String(v).padStart(2, '0');
    return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
}

function providerLabel(p) {
    const map = { catknows: 'catknows.', claude: 'Claude', openai: 'OpenAI', ollama: 'Ollama' };
    return map[p] || p;
}

function statusBadge(status, errorMsg) {
    if (status === 'success') {
        return '<span style="color:var(--color-success);" title="Success">OK</span>';
    }
    const escaped = (errorMsg || 'Error').replace(/"/g, '&quot;').replace(/</g, '&lt;');
    return `<span style="color:var(--color-error);cursor:help;" title="${escaped}">ERR</span>`;
}

// ---------------------------------------------------------------------------
// Stats cards
// ---------------------------------------------------------------------------

async function loadAiStats() {
    const container = document.getElementById('aiStatsCards');
    if (!container) return;
    try {
        const resp = await fetch('/api/ai-request-history/stats');
        if (!resp.ok) { container.innerHTML = '<span style="color:var(--color-error);">Failed to load stats.</span>'; return; }
        const s = await resp.json();

        const avgMs = s.total_requests > 0 ? Math.round(s.total_duration_ms / s.total_requests) : 0;

        container.innerHTML = `
            <div class="ai-stat-card">
                <div class="ai-stat-value">${formatNumber(s.total_requests)}</div>
                <div class="ai-stat-label">Total Requests</div>
            </div>
            <div class="ai-stat-card">
                <div class="ai-stat-value">${formatNumber(s.total_tokens)}</div>
                <div class="ai-stat-label">Total Tokens</div>
            </div>
            <div class="ai-stat-card">
                <div class="ai-stat-value">${formatDuration(avgMs)}</div>
                <div class="ai-stat-label">Avg Duration</div>
            </div>
            <div class="ai-stat-card">
                <div class="ai-stat-value">${formatNumber(s.error_count)}</div>
                <div class="ai-stat-label">Errors</div>
            </div>
            <div class="ai-stat-card">
                <div class="ai-stat-value">${formatNumber(s.last_24h.count)}</div>
                <div class="ai-stat-label">Last 24h</div>
            </div>
            <div class="ai-stat-card">
                <div class="ai-stat-value">${formatNumber(s.last_7d.count)}</div>
                <div class="ai-stat-label">Last 7 Days</div>
            </div>
        `;
    } catch (e) {
        console.error('Failed to load AI stats:', e);
        container.innerHTML = '<span style="color:var(--color-error);">Failed to load stats.</span>';
    }
}

// ---------------------------------------------------------------------------
// History table
// ---------------------------------------------------------------------------

function renderHistoryRow(e) {
    return `<tr class="ai-history-row" onclick="toggleHistoryDetail(this)">
        <td>${formatTime(e.created_at)}</td>
        <td>${providerLabel(e.provider)}</td>
        <td style="font-size:0.85em;">${e.model || '-'}</td>
        <td>${formatDuration(e.duration_ms)}</td>
        <td>${formatNumber(e.total_tokens)}</td>
        <td>${formatNumber(e.prompt_chars)}</td>
        <td>${formatNumber(e.completion_chars)}</td>
        <td>${statusBadge(e.status, e.error_message)}</td>
    </tr>
    <tr class="ai-history-detail" style="display:none;">
        <td colspan="8" style="padding:8px 12px;background:var(--color-bg-primary);font-size:0.85em;color:var(--color-text-secondary);">
            <b>Prompt tokens:</b> ${formatNumber(e.prompt_tokens)} &nbsp;|&nbsp;
            <b>Completion tokens:</b> ${formatNumber(e.completion_tokens)} &nbsp;|&nbsp;
            <b>Messages:</b> ${e.message_count} &nbsp;|&nbsp;
            <b>Session:</b> ${e.session_id > 0 ? '#' + e.session_id : '-'} &nbsp;|&nbsp;
            <b>Endpoint:</b> ${e.endpoint_url || '-'}
            ${e.error_message ? '<br><b>Error:</b> <span style="color:var(--color-error);">' + e.error_message.replace(/</g, '&lt;') + '</span>' : ''}
        </td>
    </tr>`;
}

function toggleHistoryDetail(row) {
    const detail = row.nextElementSibling;
    if (detail && detail.classList.contains('ai-history-detail')) {
        detail.style.display = detail.style.display === 'none' ? '' : 'none';
    }
}

async function loadAiHistory(reset) {
    if (reset) aiHistoryOffset = 0;

    const tbody = document.getElementById('aiHistoryBody');
    const loadMoreBtn = document.getElementById('aiHistoryLoadMore');
    const emptyMsg = document.getElementById('aiHistoryEmpty');
    if (!tbody) return;

    try {
        const resp = await fetch(`/api/ai-request-history?limit=${AI_HISTORY_PAGE_SIZE}&offset=${aiHistoryOffset}`);
        if (!resp.ok) { tbody.innerHTML = '<tr><td colspan="8" style="color:var(--color-error);">Failed to load.</td></tr>'; return; }
        const data = await resp.json();
        aiHistoryTotal = data.total;

        if (reset) tbody.innerHTML = '';

        for (const e of data.entries) {
            tbody.insertAdjacentHTML('beforeend', renderHistoryRow(e));
        }

        aiHistoryOffset += data.entries.length;

        if (loadMoreBtn) loadMoreBtn.style.display = aiHistoryOffset < aiHistoryTotal ? '' : 'none';
        if (emptyMsg) emptyMsg.style.display = aiHistoryTotal === 0 ? '' : 'none';
    } catch (e) {
        console.error('Failed to load AI history:', e);
    }
}

async function clearAiHistory() {
    if (!confirm('Delete all AI request history? This cannot be undone.')) return;
    try {
        await fetch('/api/ai-request-history', { method: 'DELETE' });
        loadAiHistory(true);
        loadAiStats();
    } catch (e) {
        console.error('Failed to clear AI history:', e);
    }
}

// ---------------------------------------------------------------------------
// Tab activation
// ---------------------------------------------------------------------------

function initAiHistoryTab() {
    loadAiStats();
    loadAiHistory(true);
}
