{% extends "base.html" %}

{% block title %}Native Prompt Cache Settings{% endblock %}

{% block content %}
<div class="container-fluid" style="padding: 20px;">
    <div style="max-width: 1400px; margin: 0 auto;">
        <h2 style="color: var(--color-text); margin-bottom: 30px;">
            <i class="fas fa-memory me-2"></i>Native Prompt Cache Settings
        </h2>

        <div style="background: rgba(59,130,246,0.12); border: 1px solid rgba(59,130,246,0.35); border-radius: 8px; padding: 16px 18px; margin-bottom: 20px; color: var(--color-text);">
            <strong>Scope note:</strong> this page controls the legacy user-specific native prompt-caching overrides used by provider adapters such as OpenAI-compatible, Claude, and Kilo flows.
            The newer request-time response-cache policy now lives in the dashboard feature overrides under <strong>Response Cache</strong>.
        </div>

        <!-- User Default Cache Setting -->
        <div style="background: var(--bg-panel); border: 2px solid #f39c12; border-radius: 8px; padding: 20px; margin-bottom: 20px;">
            <h3 style="margin: 0 0 20px 0; color: #f39c12;">
                <i class="fas fa-user-circle me-2"></i>User Default Native Cache Setting
            </h3>
            
            <div style="background: var(--bg-page); padding: 15px; border-radius: 8px; margin-bottom: 15px;">
                <div style="display: flex; align-items: center; justify-content: space-between;">
                    <div>
                        <h5 style="margin: 0 0 5px 0; color: var(--color-text);">Enable Native Prompt Caching</h5>
                        <p style="color: var(--color-muted); margin: 0; font-size: 14px;">Enable or disable provider-native prompt caching overrides for all your providers and models.</p>
                    </div>
                </div>
            </div>
            
            <div style="background: var(--bg-accent); padding: 15px; border-radius: 8px; border-left: 3px solid var(--color-link);">
                <h5 style="margin: 0 0 10px 0; color: var(--color-link);">
                    <i class="fas fa-info-circle me-2"></i>Cache Override Hierarchy
                </h5>
                <p style="color: var(--color-muted); margin: 0; font-size: 13px; line-height: 1.6;">
                    Legacy native prompt-caching settings are applied in this priority order (most specific takes precedence):
                    <br><strong>1. Model-level setting</strong> → Overrides everything
                    <br><strong>2. Provider-level setting</strong> → Overrides user default
                    <br><strong>3. User default</strong> → Applied if no specific setting exists
                    <br><strong>Default: Enabled</strong> if no settings are configured
                </p>
            </div>
                    <div class="form-check form-switch">
                        <input class="form-check-input" type="checkbox" id="globalCacheToggle" onchange="setCacheSetting(null, null, this.checked)">
                        <label class="form-check-label" for="globalCacheToggle"></label>
                    </div>
                </div>
            </div>
        </div>



        <!-- Back Button -->
        <div style="margin-top: 30px;">
            <a href="{{ url_for(request, '/dashboard') }}" class="btn btn-secondary">
                <i class="fas fa-arrow-left me-2"></i>Back to Dashboard
            </a>
        </div>
    </div>
</div>

<script>
let cacheSettings = [];

document.addEventListener('DOMContentLoaded', function() {
    loadCacheSettings();
});

async function loadCacheSettings() {
    try {
        const response = await fetch('{{ url_for(request, "/dashboard/api/cache-settings") }}', {
            credentials: 'same-origin'
        });
        const data = await response.json();
        cacheSettings = data.settings || [];
        
        console.log('Loaded cache settings:', cacheSettings);
        
        // Update global toggle - find setting where both provider_id and model_name are null
        const globalSetting = cacheSettings.find(s => s.provider_id === null && s.model_name === null);
        console.log('Global setting found:', globalSetting);
        document.getElementById('globalCacheToggle').checked = globalSetting ? globalSetting.cache_enabled : true;
    } catch (error) {
        console.error('Error loading cache settings:', error);
        showToast('Error loading cache settings', 'danger');
    }
}

async function setCacheSetting(provider_id, model_name, enabled) {
    try {
        const response = await fetch('{{ url_for(request, "/dashboard/api/cache-settings") }}', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            credentials: 'same-origin',
            body: JSON.stringify({
                provider_id: provider_id || null,
                model_name: model_name || null,
                cache_enabled: enabled
            })
        });
        
        if (response.ok) {
            showToast('Cache setting updated', 'success');
            await loadCacheSettings();
        } else {
            showToast('Failed to update setting', 'danger');
        }
    } catch (error) {
        console.error('Error updating cache setting:', error);
        showToast('Error updating setting', 'danger');
    }
}

function showToast(message, type) {
    const alertDiv = document.createElement('div');
    alertDiv.style.cssText = `
        position: fixed;
        top: 20px;
        left: 50%;
        transform: translateX(-50%);
        z-index: 10000;
        min-width: 400px;
        max-width: calc(100vw - 16px);
        padding: 20px 30px;
        ${type === 'success' ? 'background: linear-gradient(135deg, #27ae60 0%, #2ecc71 100%); color: white; border: 2px solid #27ae60;' : ''}
        ${type === 'danger' ? 'background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%); color: white; border: 2px solid #e74c3c;' : ''}
        ${type === 'warning' ? 'background: linear-gradient(135deg, #f39c12 0%, #e67e22 100%); color: white; border: 2px solid #f39c12;' : ''}
    `;
    
    const icon = type === 'success' ? 'fa-check-circle' : type === 'danger' ? 'fa-times-circle' : 'fa-exclamation-triangle';
    alertDiv.innerHTML = `<i class="fas ${icon}" style="font-size: 24px; margin-right: 10px; vertical-align: middle;"></i><span style="vertical-align: middle;">${message}</span>`;
    
    if (!document.getElementById('alertAnimations')) {
        const style = document.createElement('style');
        style.id = 'alertAnimations';
        style.textContent = `
            @keyframes slideDown {
                from {
                    opacity: 0;
                    transform: translateX(-50%) translateY(-20px);
                }
                to {
                    opacity: 1;
                    transform: translateX(-50%) translateY(0);
                }
            }
            @keyframes slideUp {
                from {
                    opacity: 1;
                    transform: translateX(-50%) translateY(0);
                }
                to {
                    opacity: 0;
                    transform: translateX(-50%) translateY(-20px);
                }
            }
        `;
        document.head.appendChild(style);
    }
    
    document.body.appendChild(alertDiv);
    
    setTimeout(() => {
        alertDiv.style.animation = 'slideUp 0.3s ease-out';
        setTimeout(() => alertDiv.remove(), 300);
    }, 4000);
}
</script>
{% endblock %}
