/**
 * Data Archive tab — stats cards, config, ZIP file table.
 * Loaded by settings.html when the "Data Archive" tab is active.
 */

function formatBytes(bytes) {
    if (bytes === 0) return '0 B';
    const units = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(1024));
    return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + units[i];
}

function formatMb(mb) {
    if (mb < 1) return mb.toFixed(2) + ' MB';
    if (mb < 1024) return mb.toFixed(1) + ' MB';
    return (mb / 1024).toFixed(2) + ' GB';
}

async function initArchiveTab() {
    const statsArea = document.getElementById('archiveStats');
    if (!statsArea) return;

    statsArea.innerHTML = '<span style="color:var(--color-text-secondary);">Loading archive stats...</span>';

    try {
        const resp = await fetch('/api/archive/stats');
        if (!resp.ok) {
            statsArea.innerHTML = '<span style="color:var(--color-error);">Failed to load stats (HTTP ' + resp.status + ')</span>';
            return;
        }
        const stats = await resp.json();

        // Render stats cards
        statsArea.innerHTML = `
            <div class="ai-stat-card">
                <div class="ai-stat-value">${formatMb(stats.db_size_mb)}</div>
                <div class="ai-stat-label">Database Size</div>
            </div>
            <div class="ai-stat-card">
                <div class="ai-stat-value">${formatMb(stats.archive_dir_size_mb)}</div>
                <div class="ai-stat-label">Archive Folder</div>
            </div>
            <div class="ai-stat-card">
                <div class="ai-stat-value">${stats.zip_count}</div>
                <div class="ai-stat-label">ZIP Files</div>
            </div>
            <div class="ai-stat-card">
                <div class="ai-stat-value">${stats.archived_fetch_count}</div>
                <div class="ai-stat-label">Archived Fetches</div>
            </div>
        `;

        // Render ZIP file table
        renderArchiveTable(stats.zip_files || []);

    } catch (e) {
        statsArea.innerHTML = '<span style="color:var(--color-error);">Failed to load archive stats.</span>';
        console.error('initArchiveTab error:', e);
    }
}

function renderArchiveTable(zipFiles) {
    const tbody = document.querySelector('#archiveTable tbody');
    if (!tbody) return;

    if (zipFiles.length === 0) {
        tbody.innerHTML = '<tr><td colspan="4" style="color:var(--color-text-secondary);text-align:center;padding:16px;">No archived files yet.</td></tr>';
        return;
    }

    tbody.innerHTML = zipFiles.map(f => {
        // Extract date from filename: rawdata_YYYY-MM-DD_HH-MM.zip
        const dateMatch = f.filename.match(/rawdata_(\d{4}-\d{2}-\d{2})_(\d{2}-\d{2})\.zip/);
        const dateStr = dateMatch ? dateMatch[1] + ' ' + dateMatch[2].replace('-', ':') : f.filename;

        return `<tr>
            <td style="font-family:monospace;font-size:0.85em;">${escapeHtml(f.filename)}</td>
            <td>${formatMb(f.size_mb)}</td>
            <td>${dateStr}</td>
            <td>
                <button onclick="downloadArchive('${escapeHtml(f.filename)}')" style="padding:3px 10px;margin-right:4px;">Download</button>
                <button onclick="deleteArchive('${escapeHtml(f.filename)}')" style="padding:3px 10px;background:var(--color-error);color:white;border:none;border-radius:var(--radius-sm);cursor:pointer;">Delete</button>
            </td>
        </tr>`;
    }).join('');
}

async function saveArchiveConfig() {
    const triggerMb = document.getElementById('archiveTriggerMb').value;
    const ageDays = document.getElementById('archiveAgeDays').value;

    try {
        await ConfigEntry.set('archive_trigger_size_mb', triggerMb);
        await ConfigEntry.set('archive_age_days', ageDays);

        const btn = document.getElementById('archiveSaveBtn');
        if (btn) {
            const orig = btn.textContent;
            btn.textContent = 'Saved!';
            btn.style.color = 'var(--color-success)';
            setTimeout(() => { btn.textContent = orig; btn.style.color = ''; }, 2000);
        }
    } catch (e) {
        console.error('saveArchiveConfig error:', e);
        alert('Failed to save config: ' + e.message);
    }
}

async function runArchiveNow() {
    const btn = document.getElementById('archiveRunBtn');
    if (btn) { btn.disabled = true; btn.textContent = 'Archiving...'; }

    try {
        const resp = await fetch('/api/archive/run', { method: 'POST' });
        const data = await resp.json();
        if (resp.ok) {
            const msg = data.archived > 0
                ? 'Archived ' + data.archived + ' records.'
                : 'No records to archive (all recent or already archived).';
            if (btn) { btn.textContent = msg; }
            setTimeout(() => {
                if (btn) { btn.disabled = false; btn.textContent = 'Archive Now'; }
            }, 3000);
            // Refresh stats
            await initArchiveTab();
        } else {
            if (btn) { btn.disabled = false; btn.textContent = 'Archive Now'; }
            alert('Archival failed: ' + (data.error || 'Unknown error'));
        }
    } catch (e) {
        if (btn) { btn.disabled = false; btn.textContent = 'Archive Now'; }
        console.error('runArchiveNow error:', e);
        alert('Archival failed: ' + e.message);
    }
}

function downloadArchive(filename) {
    // Trigger browser download via a hidden link
    const a = document.createElement('a');
    a.href = '/api/archive/download?file=' + encodeURIComponent(filename);
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}

async function deleteArchive(filename) {
    if (!confirm('Delete archive "' + filename + '"?')) return;

    try {
        const resp = await fetch('/api/archive/delete?file=' + encodeURIComponent(filename), {
            method: 'DELETE'
        });
        if (resp.ok) {
            await initArchiveTab();
        } else {
            const data = await resp.json();
            alert('Delete failed: ' + (data.error || 'Unknown error'));
        }
    } catch (e) {
        console.error('deleteArchive error:', e);
        alert('Delete failed: ' + e.message);
    }
}

async function deleteAllArchives() {
    if (!confirm('Delete ALL archive files? This cannot be undone.')) return;

    try {
        const resp = await fetch('/api/archive/delete-all', { method: 'DELETE' });
        if (resp.ok) {
            await initArchiveTab();
        } else {
            const data = await resp.json();
            alert('Delete all failed: ' + (data.error || 'Unknown error'));
        }
    } catch (e) {
        console.error('deleteAllArchives error:', e);
        alert('Delete all failed: ' + e.message);
    }
}
