<!--
Copyright (C) 2026 Stefy Lanza <stefy@nexlab.net>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
-->
{% extends "base.html" %}

{% block title %}Rate Limits - AISBF Dashboard{% endblock %}

{% block content %}
<h2 style="margin-bottom: 30px;" data-i18n="rate_limits_page.title">Adaptive Rate Limits</h2>

<div id="rate-limits-data" data-data-url="{{ url_for(request, '/dashboard/rate-limits/data') }}" style="display:none;"></div>

<!-- Quick Links Navigation -->
<div style="background: var(--bg-page); padding: 15px; border-radius: 8px; margin-bottom: 30px;">
    <div style="display: flex; gap: 15px; flex-wrap: wrap;">
        <a href="{{ url_for(request, '/dashboard/analytics') }}" class="btn btn-secondary" style="text-decoration: none;">
            📊 <span data-i18n="rate_limits_page.analytics">Analytics</span>
        </a>
        <a href="{{ url_for(request, '/dashboard/prompt-analytics') }}" class="btn btn-secondary" style="text-decoration: none;">
            🧠 Prompt Analytics
        </a>
        {% if session.get('role') == 'admin' and session.get('user_id') is none %}
        <a href="{{ url_for(request, '/dashboard/traffic-visits') }}" class="btn btn-secondary" style="text-decoration: none;">
            👣 Traffic &amp; Visits
        </a>
        {% endif %}
        <a href="{{ url_for(request, '/dashboard/response-cache') }}" class="btn btn-secondary" style="text-decoration: none;">
            💾 <span data-i18n="rate_limits_page.response_cache">Response Cache</span>
        </a>
        <a href="{{ url_for(request, '/dashboard/rate-limits') }}" class="btn" style="text-decoration: none;">
            ⏱️ <span data-i18n="rate_limits_page.rate_limits">Rate Limits</span>
        </a>
    </div>
</div>

<div style="margin-bottom: 20px;">
    <button onclick="loadRateLimits()" class="btn" data-i18n="rate_limits_page.refresh">Refresh</button>
    <button onclick="clearAllRateLimiters()" class="btn btn-secondary" data-i18n="rate_limits_page.reset_all">Reset All Rate Limiters</button>
</div>

<div id="rate-limits-content">
    <p>Loading rate limit data...</p>
</div>

<style>
    .rate-limit-card {
        background: var(--bg-panel);
        border: 1px solid var(--color-border);
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 15px;
    }
    .rate-limit-card h4 {
        margin-top: 0;
        color: var(--color-text);
    }
    .stat-row {
        display: flex;
        justify-content: space-between;
        padding: 5px 0;
        border-bottom: 1px solid var(--color-border);
    }
    .stat-label {
        font-weight: 500;
        color: var(--color-muted);
    }
    .stat-value {
        color: var(--color-text);
    }
    .status-enabled {
        color: #27ae60;
        font-weight: bold;
    }
    .status-disabled {
        color: var(--alert-error-fg);
        font-weight: bold;
    }
</style>

<script>
const dataUrl = document.getElementById('rate-limits-data').dataset.dataUrl;

async function loadRateLimits() {
    const content = document.getElementById('rate-limits-content');
    content.innerHTML = `<p>${window.i18n.t('rate_limits.loading')}</p>`;

    try {
        const response = await fetch(dataUrl);
        const data = await response.json();
        
        if (Object.keys(data).length === 0) {
            content.innerHTML = `<p>${window.i18n.t('rate_limits.no_data')}</p>`;
            return;
        }
        
        let html = '';
        
        for (const [providerId, stats] of Object.entries(data)) {
            const enabledClass = stats.enabled ? 'status-enabled' : 'status-disabled';
            const last429 = stats.last_429_time ? new Date(stats.last_429_time * 1000).toLocaleString() : window.i18n.t('rate_limits_page.never');
            
            html += `
                <div class="rate-limit-card">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <h4>${window.i18n.t('rate_limits_page.provider_label')} ${providerId}</h4>
                        <button class="btn-danger" onclick="resetRateLimiter('${providerId}')" data-i18n="rate_limits_page.reset">${window.i18n.t('rate_limits_page.reset')}</button>
                    </div>
                    <div class="stat-row">
                        <span class="stat-label">${window.i18n.t('rate_limits_page.enabled')}</span>
                        <span class="stat-value ${enabledClass}">${stats.enabled ? window.i18n.t('rate_limits_page.yes') : window.i18n.t('rate_limits_page.no')}</span>
                    </div>
                    <div class="stat-row">
                        <span class="stat-label">${window.i18n.t('rate_limits_page.current_rate_limit')}</span>
                        <span class="stat-value">${stats.current_rate_limit.toFixed(2)} ${window.i18n.t('rate_limits_page.col_delay').toLowerCase()}</span>
                    </div>
                    <div class="stat-row">
                        <span class="stat-label">${window.i18n.t('rate_limits_page.base_rate_limit')}</span>
                        <span class="stat-value">${stats.base_rate_limit.toFixed(2)} ${window.i18n.t('rate_limits_page.col_delay').toLowerCase()}</span>
                    </div>
                    <div class="stat-row">
                        <span class="stat-label">${window.i18n.t('rate_limits_page.total_429')}</span>
                        <span class="stat-value">${stats.total_429_count}</span>
                    </div>
                    <div class="stat-row">
                        <span class="stat-label">${window.i18n.t('rate_limits_page.total_requests')}</span>
                        <span class="stat-value">${stats.total_requests}</span>
                    </div>
                    <div class="stat-row">
                        <span class="stat-label">${window.i18n.t('rate_limits_page.consecutive_429')}</span>
                        <span class="stat-value">${stats.consecutive_429s}</span>
                    </div>
                    <div class="stat-row">
                        <span class="stat-label">${window.i18n.t('rate_limits_page.consecutive_success')}</span>
                        <span class="stat-value">${stats.consecutive_successes}</span>
                    </div>
                    <div class="stat-row">
                        <span class="stat-label">${window.i18n.t('rate_limits_page.recent_429')}</span>
                        <span class="stat-value">${stats.recent_429_count}</span>
                    </div>
                    <div class="stat-row">
                        <span class="stat-label">${window.i18n.t('rate_limits_page.last_429')}</span>
                        <span class="stat-value">${last429}</span>
                    </div>
                </div>
            `;
        }
        
        content.innerHTML = html;
    } catch (error) {
        content.innerHTML = `<p style="color: red;">Error loading rate limits: ${error.message}</p>`;
    }
}

async function resetRateLimiter(providerId) {
    const ok = await showConfirm(window.i18n.interpolate(window.i18n.t('rate_limits_page.reset_confirm'), {provider: providerId}), window.i18n.t('rate_limits_page.reset_confirm_title'));
    if (!ok) return;
    
    try {
        const response = await fetch(`/dashboard/rate-limits/${providerId}/reset`, {
            method: 'POST'
        });
        const data = await response.json();
        
        if (data.success) {
            showAlert(data.message, 'Done', '✅', 'info');
            loadRateLimits();
        } else {
            showAlert('Error: ' + data.error, 'Error', '❌', 'danger');
        }
    } catch (error) {
        showAlert('Error: ' + error.message, 'Error', '❌', 'danger');
    }
}

async function clearAllRateLimiters() {
    const ok = await showDangerConfirm(window.i18n.t('rate_limits_page.reset_all_confirm'), window.i18n.t('rate_limits_page.reset_all_title'));
    if (!ok) return;
    
    const content = document.getElementById('rate-limits-content');
    const providerIds = [];
    
    // First get the list of providers
    try {
        const response = await fetch(dataUrl);
        const data = await response.json();
        
        for (const providerId of Object.keys(data)) {
            try {
                await fetch(`/dashboard/rate-limits/${providerId}/reset`, {
                    method: 'POST'
                });
            } catch (e) {
                console.error(`Failed to reset ${providerId}:`, e);
            }
        }
        
        showAlert(window.i18n.t('rate_limits_page.reset_all_success'), 'Done', '✅', 'info');
        loadRateLimits();
    } catch (error) {
        showAlert('Error: ' + error.message, 'Error', '❌', 'danger');
    }
}

// Load on page load
loadRateLimits();

// Auto-refresh every 30 seconds
setInterval(loadRateLimits, 30000);
</script>
{% endblock %}
