{% extends "base.html" %}

{% block title %}Archive - {% if current_project == all_projects_value %}All Projects{% else %}{{ current_project|display_name }}{% endif %} - CodeContext{% endblock %}

{% block content %}
<div class="archive-page">
    <h1>Memory Archive{% if current_project == all_projects_value %} - All Projects{% endif %}</h1>

    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-value">{{ stats.total }}</div>
            <div class="stat-label">Archived</div>
        </div>
        <div class="stat-card">
            <div class="stat-value">{{ stats.by_reason.get('conflict_resolution', 0) }}</div>
            <div class="stat-label">From Conflicts</div>
        </div>
        <div class="stat-card">
            <div class="stat-value">{{ stats.by_reason.get('consolidation', 0) }}</div>
            <div class="stat-label">From Consolidation</div>
        </div>
        <div class="stat-card">
            <div class="stat-value">{{ stats.by_reason.get('manual', 0) }}</div>
            <div class="stat-label">Manual</div>
        </div>
    </div>

    <!-- Filter Tabs -->
    <div class="archive-tabs">
        <a href="/archive?project={{ current_project }}&reason="
           class="archive-tab {% if not reason_filter %}active{% endif %}">
            All
        </a>
        <a href="/archive?project={{ current_project }}&reason=conflict_resolution"
           class="archive-tab {% if reason_filter == 'conflict_resolution' %}active{% endif %}">
            Conflict Resolution
        </a>
        <a href="/archive?project={{ current_project }}&reason=consolidation"
           class="archive-tab {% if reason_filter == 'consolidation' %}active{% endif %}">
            Consolidation
        </a>
        <a href="/archive?project={{ current_project }}&reason=manual"
           class="archive-tab {% if reason_filter == 'manual' %}active{% endif %}">
            Manual
        </a>
    </div>

    <div class="archive-list" id="archive-list">
        {% if archived_memories %}
        {% for m in archived_memories %}
        <div class="archive-card" data-memory-id="{{ m.id }}">
            <div class="archive-card-header">
                <span class="type-badge type-{{ m.type }}">{{ m.type }}</span>
                <span class="archive-reason-badge reason-{{ m.deletion_reason }}">
                    {{ m.deletion_reason|replace('_', ' ')|title }}
                </span>
                {% if m.project and current_project == all_projects_value %}
                <span class="project-tag">{{ m.project|display_name }}</span>
                {% endif %}
                <span class="memory-date" data-utc-time="{{ m.deleted_at }}" data-time-prefix="Deleted: ">
                    Deleted: {{ m.deleted_at[:10] if m.deleted_at else 'Unknown' }}
                </span>
            </div>

            <h4 class="archive-title">{{ m.title }}</h4>
            <p class="archive-fact">{{ m.fact }}</p>

            {% if m.files %}
            <div class="archive-files">
                {% for f in m.files if f %}
                <code>{{ f }}</code>
                {% endfor %}
            </div>
            {% endif %}

            <div class="archive-metadata">
                {% if m.replaced_by_id %}
                <span class="metadata-item" title="This memory was replaced by another">
                    <strong>Replaced by:</strong> {{ m.replaced_by_id[:30] }}...
                </span>
                {% endif %}
                {% if m.conflict_id %}
                <span class="metadata-item">
                    <strong>Conflict:</strong> {{ m.conflict_id }}
                </span>
                {% endif %}
                {% if m.cluster_id %}
                <span class="metadata-item">
                    <strong>Cluster:</strong> {{ m.cluster_id }}
                </span>
                {% endif %}
                {% if m.reasoning %}
                <span class="metadata-item metadata-reasoning" title="{{ m.reasoning }}">
                    <strong>Reason:</strong> {{ m.reasoning[:80] }}{% if m.reasoning|length > 80 %}...{% endif %}
                </span>
                {% endif %}
            </div>

            <div class="archive-actions">
                <button class="btn btn-restore"
                        onclick="restoreMemory('{{ m.id }}', '{{ m.project or current_project }}')"
                        title="Restore this memory to the active store">
                    Restore
                </button>
                <button class="btn btn-danger"
                        onclick="permanentlyDelete('{{ m.id }}', '{{ m.project or current_project }}')"
                        title="Permanently delete (cannot be undone)">
                    Delete Forever
                </button>
            </div>
        </div>
        {% endfor %}
        {% else %}
        <div class="empty-state">
            {% if reason_filter %}
            <p>No archived memories with reason "{{ reason_filter|replace('_', ' ') }}".</p>
            {% else %}
            <p>No archived memories. Deleted memories will appear here.</p>
            {% endif %}
        </div>
        {% endif %}
    </div>

    {% if has_more %}
    <div class="load-more">
        <button class="btn btn-secondary" onclick="loadMore()">Load More</button>
    </div>
    {% endif %}
</div>

<script>
const currentProject = '{{ current_project }}';
const allProjectsValue = '{{ all_projects_value }}';
const reasonFilter = '{{ reason_filter or "" }}';
let currentOffset = {{ archived_memories|length }};

async function restoreMemory(memoryId, project) {
    if (!confirm('Restore this memory to the active store?')) return;

    try {
        const response = await fetch(`/api/archive/${memoryId}/restore?project=${encodeURIComponent(project)}`, {
            method: 'POST'
        });
        const data = await response.json();

        if (data.success) {
            showToast(`Restored as ${data.restored_id}`, 'success');
            // Remove the card from the list
            const card = document.querySelector(`[data-memory-id="${memoryId}"]`);
            if (card) card.remove();
            // Update stats
            updateStats();
        } else {
            showToast(data.error || 'Failed to restore', 'error');
        }
    } catch (err) {
        console.error('Restore error:', err);
        showToast('Network error', 'error');
    }
}

async function permanentlyDelete(memoryId, project) {
    if (!confirm('Permanently delete this memory? This cannot be undone!')) return;

    try {
        const response = await fetch(`/api/archive/${memoryId}?project=${encodeURIComponent(project)}`, {
            method: 'DELETE'
        });
        const data = await response.json();

        if (data.permanently_deleted) {
            showToast('Permanently deleted', 'success');
            // Remove the card from the list
            const card = document.querySelector(`[data-memory-id="${memoryId}"]`);
            if (card) card.remove();
            // Update stats
            updateStats();
        } else {
            showToast('Failed to delete', 'error');
        }
    } catch (err) {
        console.error('Delete error:', err);
        showToast('Network error', 'error');
    }
}

async function loadMore() {
    try {
        let url = `/api/archive?project=${encodeURIComponent(currentProject)}&offset=${currentOffset}&limit=20`;
        if (reasonFilter) url += `&reason=${encodeURIComponent(reasonFilter)}`;

        const response = await fetch(url);
        const data = await response.json();

        if (data.memories && data.memories.length > 0) {
            const list = document.getElementById('archive-list');
            data.memories.forEach(m => {
                const card = createArchiveCard(m, currentProject);
                list.appendChild(card);
            });
            currentOffset += data.memories.length;

            // Hide load more if no more data
            if (!data.has_more) {
                document.querySelector('.load-more').style.display = 'none';
            }
        }
    } catch (err) {
        console.error('Load more error:', err);
        showToast('Failed to load more', 'error');
    }
}

async function updateStats() {
    try {
        const response = await fetch(`/api/archive/stats?project=${encodeURIComponent(currentProject)}`);
        const data = await response.json();

        // Update stat cards
        const statValues = document.querySelectorAll('.stat-card .stat-value');
        if (statValues[0]) statValues[0].textContent = data.total || 0;
        if (statValues[1]) statValues[1].textContent = (data.by_reason || {}).conflict_resolution || 0;
        if (statValues[2]) statValues[2].textContent = (data.by_reason || {}).consolidation || 0;
        if (statValues[3]) statValues[3].textContent = (data.by_reason || {}).manual || 0;
    } catch (err) {
        console.error('Update stats error:', err);
    }
}

// Track known archive items for efficient refresh
let knownArchiveIds = new Set(
    Array.from(document.querySelectorAll('.archive-card')).map(c => c.dataset.memoryId)
);

// API-based refresh - fetches archive and updates DOM without page reload
async function updateArchiveList() {
    try {
        let url = `/api/archive?project=${encodeURIComponent(currentProject)}&limit=${currentOffset || 20}`;
        if (reasonFilter) url += `&reason=${encodeURIComponent(reasonFilter)}`;

        const response = await fetch(url);
        const data = await response.json();

        const archiveList = document.getElementById('archive-list');
        const newArchiveIds = new Set(data.memories.map(m => m.id));

        // Check if anything changed
        const addedIds = [...newArchiveIds].filter(id => !knownArchiveIds.has(id));
        const removedIds = [...knownArchiveIds].filter(id => !newArchiveIds.has(id));

        if (addedIds.length === 0 && removedIds.length === 0) {
            // No changes to archive list, just update stats
            updateStats();
            return;
        }

        // Remove cards that no longer exist (restored or permanently deleted)
        removedIds.forEach(id => {
            const card = document.querySelector(`[data-memory-id="${id}"]`);
            if (card) card.remove();
        });

        // Add new cards at the top
        addedIds.forEach(id => {
            const memory = data.memories.find(m => m.id === id);
            if (memory) {
                const card = createArchiveCard(memory, currentProject);
                // Remove empty state if it exists
                const emptyState = archiveList.querySelector('.empty-state');
                if (emptyState) {
                    emptyState.remove();
                }
                archiveList.insertBefore(card, archiveList.firstChild);
            }
        });

        // Update known IDs
        knownArchiveIds = newArchiveIds;

        // Handle empty state
        const existingEmpty = archiveList.querySelector('.empty-state');
        if (data.memories.length === 0) {
            if (!existingEmpty) {
                const emptyDiv = document.createElement('div');
                emptyDiv.className = 'empty-state';
                if (reasonFilter) {
                    emptyDiv.innerHTML = `<p>No archived memories with reason "${reasonFilter.replace('_', ' ')}".</p>`;
                } else {
                    emptyDiv.innerHTML = '<p>No archived memories. Deleted memories will appear here.</p>';
                }
                archiveList.appendChild(emptyDiv);
            }
        } else if (existingEmpty) {
            existingEmpty.remove();
        }

        // Update stats to keep them current
        updateStats();

    } catch (err) {
        console.error('Failed to update archive list:', err);
    }
}

// Start polling via PollingManager (2000ms interval since archive changes less frequently)
function startAutoRefresh() {
    PollingManager.subscribe('archive-list', updateArchiveList, 2000);
}

// Stop polling via PollingManager
function stopAutoRefresh() {
    PollingManager.unsubscribe('archive-list');
}

// Start auto-refresh on page load
startAutoRefresh();

</script>
{% endblock %}
