{% extends "base.html" %}

{% block title %}Summaries - {{ current_project|display_name }} - CodeContext{% endblock %}

{% block content %}
<div class="summaries-page">
    <h1>Project Summaries</h1>
    <p class="page-description">
        Evolving project summaries that inject context at session start.
    </p>

    {% if current_project == all_projects_value %}
    <div class="warning-banner">
        <p>Please select a specific project to view summaries.</p>
    </div>
    {% else %}

    <!-- Stats Grid -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-value">v{{ stats.version if stats.version else 0 }}</div>
            <div class="stat-label">Summary Version</div>
        </div>
        <div class="stat-card">
            <div class="stat-value">{{ "{:,}".format(stats.token_count) if stats.token_count else 0 }}</div>
            <div class="stat-label">Summary Tokens</div>
        </div>
        <div class="stat-card">
            <div class="stat-value">{{ "{:,}".format(stats.memory_token_count) if stats.memory_token_count else 0 }}</div>
            <div class="stat-label">Memory Tokens</div>
        </div>
        <div class="stat-card">
            <div class="stat-value">{{ info.memory_count if info else 0 }}</div>
            <div class="stat-label">Total Memories</div>
        </div>
    </div>

    <!-- Current Summary Section -->
    <div class="summary-section">
        <div class="section-header">
            <h2>Current Summary</h2>
            <div class="section-actions">
                <button id="regenerate-btn" class="btn btn-primary" onclick="regenerateSummary()">
                    <span class="btn-text">Regenerate</span>
                    <span class="btn-spinner" style="display: none;">
                        <span class="spinner"></span>
                        <span>Generating...</span>
                    </span>
                </button>
            </div>
        </div>

        {% if summary %}
        <div class="summary-card">
            <div class="summary-meta">
                <span class="summary-version">Version {{ summary.version }}</span>
                <span class="summary-date" data-utc-time="{{ summary.generated_at }}">
                    {{ summary.generated_at | format_datetime }}
                </span>
                <span class="summary-trigger trigger-{{ summary.trigger }}">{{ summary.trigger }}</span>
                {% if summary.pending %}
                <span class="summary-pending">PENDING</span>
                {% endif %}
            </div>
            <div class="summary-content" id="summary-content">
                <pre>{{ summary.summary }}</pre>
            </div>
            <div class="summary-actions">
                <button class="btn btn-sm btn-secondary" onclick="copySummary()">
                    Copy
                </button>
                <button class="btn btn-sm btn-secondary" onclick="toggleSummaryExpand()">
                    Expand
                </button>
            </div>
        </div>
        {% else %}
        <div class="empty-state">
            <p>No summary generated yet.</p>
            <p>Click "Regenerate" to create the first summary, or it will be generated automatically at session end.</p>
        </div>
        {% endif %}
    </div>

    <!-- Version History Section -->
    <div class="history-section">
        <h2>Version History</h2>

        {% if history %}
        <div class="history-table-wrapper">
            <table class="history-table">
                <thead>
                    <tr>
                        <th>Version</th>
                        <th>Date</th>
                        <th>Memories</th>
                        <th>New</th>
                        <th>Trigger</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    {% for h in history %}
                    <tr>
                        <td>v{{ h.version }}</td>
                        <td data-utc-time="{{ h.generated_at }}">{{ h.generated_at | format_datetime }}</td>
                        <td>{{ h.memory_count }}</td>
                        <td>+{{ h.new_memories_count }}</td>
                        <td><span class="trigger-badge trigger-{{ h.trigger }}">{{ h.trigger }}</span></td>
                        <td>
                            <button class="btn btn-sm btn-secondary" onclick="viewVersion({{ h.version }})">View</button>
                            <button class="btn btn-sm btn-secondary" onclick="useVersion({{ h.version }})">Use</button>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        {% else %}
        <div class="empty-state">
            <p>No version history yet. History is saved when summaries are regenerated.</p>
        </div>
        {% endif %}
    </div>

    <!-- Settings Section -->
    <div class="settings-section">
        <h2>Summary Settings</h2>

        <div class="settings-card">
            <div class="setting-row">
                <label class="toggle-switch">
                    <input type="checkbox" id="summary-enabled" {% if settings.enabled %}checked{% endif %} onchange="updateSettings()">
                    <span class="toggle-slider"></span>
                </label>
                <span class="setting-label">Enable Summary Injection</span>
                <span class="setting-hint">(injects summary at session start)</span>
            </div>

            <div class="setting-row">
                <label class="toggle-switch">
                    <input type="checkbox" id="auto-generate" {% if settings.auto_generate_on_session_end %}checked{% endif %} onchange="updateSettings()">
                    <span class="toggle-slider"></span>
                </label>
                <span class="setting-label">Auto-generate on Session End</span>
                <span class="setting-hint">(updates summary when new memories exist)</span>
            </div>

            <div class="setting-row">
                <label for="timeline-items">Timeline Items:</label>
                <select id="timeline-items" onchange="updateSettings()">
                    <option value="5" {% if settings.timeline_items == 5 %}selected{% endif %}>5</option>
                    <option value="10" {% if settings.timeline_items == 10 %}selected{% endif %}>10</option>
                    <option value="15" {% if settings.timeline_items == 15 %}selected{% endif %}>15</option>
                    <option value="20" {% if settings.timeline_items == 20 %}selected{% endif %}>20</option>
                </select>
                <span class="setting-hint">(recent memories shown in timeline)</span>
            </div>

            <div class="setting-row">
                <label for="max-tokens">Max Summary Tokens:</label>
                <select id="max-tokens" onchange="updateSettings()">
                    <option value="500" {% if settings.max_tokens == 500 %}selected{% endif %}>500</option>
                    <option value="1000" {% if settings.max_tokens == 1000 %}selected{% endif %}>1000</option>
                    <option value="1500" {% if settings.max_tokens == 1500 %}selected{% endif %}>1500</option>
                    <option value="2000" {% if settings.max_tokens == 2000 %}selected{% endif %}>2000</option>
                </select>
                <span class="setting-hint">(target summary length)</span>
            </div>

            <div class="setting-row">
                <label for="full-regen-memories">Full Regen Every N Memories:</label>
                <select id="full-regen-memories" onchange="updateSettings()">
                    <option value="0" {% if settings.full_regen_every_n_memories == 0 %}selected{% endif %}>Disabled</option>
                    <option value="25" {% if settings.full_regen_every_n_memories == 25 %}selected{% endif %}>25</option>
                    <option value="50" {% if settings.full_regen_every_n_memories == 50 %}selected{% endif %}>50</option>
                    <option value="100" {% if settings.full_regen_every_n_memories == 100 %}selected{% endif %}>100</option>
                </select>
                <span class="setting-hint">(regenerate from scratch periodically)</span>
            </div>
        </div>
    </div>
    {% endif %}
</div>

<!-- Version View Modal -->
<div id="version-modal" class="modal" style="display: none;">
    <div class="modal-backdrop" onclick="closeVersionModal()"></div>
    <div class="modal-content modal-large">
        <div class="modal-header">
            <h3>Summary Version <span id="modal-version">?</span></h3>
            <button class="modal-close" onclick="closeVersionModal()">&times;</button>
        </div>
        <div class="modal-body">
            <div class="modal-meta">
                <span id="modal-date"></span>
                <span id="modal-trigger"></span>
                <span id="modal-memories"></span>
            </div>
            <div class="modal-summary">
                <pre id="modal-content"></pre>
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn btn-secondary" onclick="closeVersionModal()">Close</button>
            <button class="btn btn-primary" id="modal-use-btn" onclick="useVersionFromModal()">Use This Version</button>
        </div>
    </div>
</div>

<script>
const currentProject = '{{ current_project }}';
let currentModalVersion = null;

async function regenerateSummary() {
    const btn = document.getElementById('regenerate-btn');
    const btnText = btn.querySelector('.btn-text');
    const btnSpinner = btn.querySelector('.btn-spinner');

    btn.disabled = true;
    btnText.style.display = 'none';
    btnSpinner.style.display = 'inline-flex';

    try {
        const response = await fetch(
            `/api/summary/regenerate?project=${encodeURIComponent(currentProject)}&force_full=false`,
            { method: 'POST' }
        );
        const data = await response.json();

        if (response.ok && data.success) {
            showToast(`Summary v${data.version} generated!`, 'success');
            setTimeout(() => window.location.reload(), 1000);
        } else {
            showToast(data.message || 'No new memories to summarize', 'info');
            restoreButton(btn, btnText, btnSpinner);
        }
    } catch (err) {
        console.error('Regenerate error:', err);
        showToast('Network error', 'error');
        restoreButton(btn, btnText, btnSpinner);
    }
}

async function viewVersion(version) {
    try {
        const response = await fetch(`/api/summary/history/${version}?project=${encodeURIComponent(currentProject)}`);
        const data = await response.json();

        if (response.ok && data.version) {
            currentModalVersion = version;
            document.getElementById('modal-version').textContent = 'v' + data.version.version;
            document.getElementById('modal-date').textContent = formatLocalTime(data.version.generated_at);
            document.getElementById('modal-trigger').textContent = data.version.trigger;
            document.getElementById('modal-memories').textContent = `${data.version.memory_count} memories`;
            document.getElementById('modal-content').textContent = data.version.summary;
            document.getElementById('version-modal').style.display = 'flex';
        } else {
            showToast('Version not found', 'error');
        }
    } catch (err) {
        console.error('View version error:', err);
        showToast('Network error', 'error');
    }
}

async function useVersion(version) {
    if (!confirm(`Use version ${version} as the current summary? The current summary will be saved to history.`)) {
        return;
    }

    try {
        const response = await fetch(
            `/api/summary/use/${version}?project=${encodeURIComponent(currentProject)}`,
            { method: 'POST' }
        );
        const data = await response.json();

        if (response.ok && data.success) {
            showToast(`Now using version ${version}`, 'success');
            setTimeout(() => window.location.reload(), 1000);
        } else {
            showToast('Failed to use version', 'error');
        }
    } catch (err) {
        console.error('Use version error:', err);
        showToast('Network error', 'error');
    }
}

function useVersionFromModal() {
    if (currentModalVersion) {
        closeVersionModal();
        useVersion(currentModalVersion);
    }
}

function closeVersionModal() {
    document.getElementById('version-modal').style.display = 'none';
    currentModalVersion = null;
}

function copySummary() {
    const content = document.getElementById('summary-content');
    const text = content.querySelector('pre').textContent;

    navigator.clipboard.writeText(text).then(() => {
        showToast('Summary copied to clipboard', 'success');
    }).catch(() => {
        showToast('Failed to copy', 'error');
    });
}

function toggleSummaryExpand() {
    const content = document.getElementById('summary-content');
    content.classList.toggle('expanded');
}

async function updateSettings() {
    const enabled = document.getElementById('summary-enabled').checked;
    const autoGenerate = document.getElementById('auto-generate').checked;
    const timelineItems = parseInt(document.getElementById('timeline-items').value);
    const maxTokens = parseInt(document.getElementById('max-tokens').value);
    const fullRegenMemories = parseInt(document.getElementById('full-regen-memories').value);

    try {
        const params = new URLSearchParams({
            enabled: enabled,
            auto_generate_on_session_end: autoGenerate,
            full_regen_every_n_sessions: 0,
            full_regen_every_n_memories: fullRegenMemories,
            max_tokens: maxTokens,
            timeline_items: timelineItems
        });

        const response = await fetch(`/api/settings/summary?${params}`, { method: 'POST' });

        if (response.ok) {
            showToast('Settings saved', 'success');
        } else {
            showToast('Failed to save settings', 'error');
        }
    } catch (err) {
        console.error('Settings error:', err);
        showToast('Network error', 'error');
    }
}

function restoreButton(btn, btnText, btnSpinner) {
    btn.disabled = false;
    btnText.style.display = 'inline';
    btnSpinner.style.display = 'none';
}

// Close modal on Escape
document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
        closeVersionModal();
    }
});
</script>

<style>
/* Summaries page specific styles */
.summaries-page {
    max-width: 1200px;
    margin: 0 auto;
}

.summary-section,
.history-section,
.settings-section {
    margin-bottom: 2rem;
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1rem;
}

.section-header h2 {
    margin: 0;
}

.summary-card {
    background: var(--card-bg);
    border: 1px solid var(--border-color);
    border-radius: 8px;
    padding: 1.5rem;
}

.summary-meta {
    display: flex;
    gap: 1rem;
    align-items: center;
    margin-bottom: 1rem;
    flex-wrap: wrap;
}

.summary-version {
    font-weight: 600;
    color: var(--accent-color);
}

.summary-date {
    color: var(--text-muted);
}

.summary-trigger {
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 0.8rem;
    background: var(--bg-secondary);
}

.trigger-session_end { background: #e3f2fd; color: #1565c0; }
.trigger-manual { background: #fce4ec; color: #c2185b; }
.trigger-scheduled { background: #f3e5f5; color: #7b1fa2; }
.trigger-rollback { background: #fff3e0; color: #ef6c00; }

[data-theme="dark"] .trigger-session_end { background: #1565c0; color: #e3f2fd; }
[data-theme="dark"] .trigger-manual { background: #c2185b; color: #fce4ec; }
[data-theme="dark"] .trigger-scheduled { background: #7b1fa2; color: #f3e5f5; }
[data-theme="dark"] .trigger-rollback { background: #ef6c00; color: #fff3e0; }

.summary-pending {
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 0.8rem;
    background: #ffeb3b;
    color: #000;
    font-weight: 600;
}

.summary-content {
    background: var(--bg-secondary);
    border-radius: 4px;
    padding: 1rem;
    max-height: 300px;
    overflow-y: auto;
    margin-bottom: 1rem;
}

.summary-content.expanded {
    max-height: none;
}

.summary-content pre {
    margin: 0;
    white-space: pre-wrap;
    word-wrap: break-word;
    font-family: inherit;
    font-size: 0.9rem;
    line-height: 1.6;
}

.summary-actions {
    display: flex;
    gap: 0.5rem;
}

/* History table */
.history-table-wrapper {
    overflow-x: auto;
}

.history-table {
    width: 100%;
    border-collapse: collapse;
    background: var(--card-bg);
    border-radius: 8px;
    overflow: hidden;
}

.history-table th,
.history-table td {
    padding: 0.75rem 1rem;
    text-align: left;
    border-bottom: 1px solid var(--border-color);
}

.history-table th {
    background: var(--bg-secondary);
    font-weight: 600;
}

.history-table tr:last-child td {
    border-bottom: none;
}

.history-table tr:hover {
    background: var(--bg-hover);
}

.trigger-badge {
    padding: 2px 6px;
    border-radius: 3px;
    font-size: 0.75rem;
}

/* Settings */
.settings-card {
    background: var(--card-bg);
    border: 1px solid var(--border-color);
    border-radius: 8px;
    padding: 1.5rem;
}

.setting-row {
    display: flex;
    align-items: center;
    gap: 1rem;
    padding: 0.75rem 0;
    border-bottom: 1px solid var(--border-color);
}

.setting-row:last-child {
    border-bottom: none;
}

.setting-label {
    font-weight: 500;
    min-width: 200px;
}

.setting-hint {
    color: var(--text-muted);
    font-size: 0.85rem;
}

.setting-row select {
    padding: 0.5rem;
    border: 1px solid var(--border-color);
    border-radius: 4px;
    background: var(--card-bg);
    color: var(--text-color);
}

/* Toggle switch */
.toggle-switch {
    position: relative;
    display: inline-block;
    width: 50px;
    height: 26px;
    flex-shrink: 0;
}

.toggle-switch input {
    opacity: 0;
    width: 0;
    height: 0;
}

.toggle-slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: var(--bg-secondary);
    transition: 0.3s;
    border-radius: 26px;
}

.toggle-slider:before {
    position: absolute;
    content: "";
    height: 20px;
    width: 20px;
    left: 3px;
    bottom: 3px;
    background-color: white;
    transition: 0.3s;
    border-radius: 50%;
}

input:checked + .toggle-slider {
    background-color: var(--accent-color);
}

input:checked + .toggle-slider:before {
    transform: translateX(24px);
}

/* Modal */
.modal {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 1000;
    align-items: center;
    justify-content: center;
}

.modal-backdrop {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
}

.modal-content {
    position: relative;
    background: var(--card-bg);
    border-radius: 8px;
    max-width: 800px;
    width: 90%;
    max-height: 80vh;
    display: flex;
    flex-direction: column;
}

.modal-large {
    max-width: 900px;
}

.modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1rem 1.5rem;
    border-bottom: 1px solid var(--border-color);
}

.modal-header h3 {
    margin: 0;
}

.modal-close {
    background: none;
    border: none;
    font-size: 1.5rem;
    cursor: pointer;
    color: var(--text-muted);
    padding: 0;
    line-height: 1;
}

.modal-close:hover {
    color: var(--text-color);
}

.modal-body {
    padding: 1.5rem;
    overflow-y: auto;
    flex: 1;
}

.modal-meta {
    display: flex;
    gap: 1rem;
    margin-bottom: 1rem;
    color: var(--text-muted);
}

.modal-summary {
    background: var(--bg-secondary);
    border-radius: 4px;
    padding: 1rem;
}

.modal-summary pre {
    margin: 0;
    white-space: pre-wrap;
    word-wrap: break-word;
    font-family: inherit;
    font-size: 0.9rem;
    line-height: 1.6;
}

.modal-footer {
    display: flex;
    justify-content: flex-end;
    gap: 0.5rem;
    padding: 1rem 1.5rem;
    border-top: 1px solid var(--border-color);
}

/* Toast notifications */
.toast {
    position: fixed;
    bottom: 20px;
    right: 20px;
    padding: 12px 24px;
    border-radius: 4px;
    background: var(--card-bg);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    transform: translateY(100px);
    opacity: 0;
    transition: all 0.3s ease;
    z-index: 1001;
}

.toast.show {
    transform: translateY(0);
    opacity: 1;
}

.toast-success { border-left: 4px solid #4caf50; }
.toast-error { border-left: 4px solid #f44336; }
.toast-info { border-left: 4px solid #2196f3; }

/* Warning banner */
.warning-banner {
    background: #fff3e0;
    border: 1px solid #ffcc80;
    border-radius: 8px;
    padding: 1rem;
    margin-bottom: 1rem;
    color: #e65100;
}

[data-theme="dark"] .warning-banner {
    background: #3e2723;
    border-color: #5d4037;
    color: #ffcc80;
}

/* Empty state */
.empty-state {
    text-align: center;
    padding: 2rem;
    background: var(--bg-secondary);
    border-radius: 8px;
    color: var(--text-muted);
}

/* Button spinner */
.btn-spinner {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
}

.spinner {
    width: 16px;
    height: 16px;
    border: 2px solid rgba(255, 255, 255, 0.3);
    border-top-color: white;
    border-radius: 50%;
    animation: spin 0.8s linear infinite;
}

@keyframes spin {
    to { transform: rotate(360deg); }
}
</style>
{% endblock %}
