// Метрики и мониторинг
let metricsInterval = null;

async function refreshMetrics() {
    try {
        const response = await fetch('/api/metrics/summary');
        const data = await response.json();
        
        if (data.success) {
            updateMetricsWidgets(data.metrics);
        } else {
            console.error('Ошибка загрузки метрик:', data.error);
        }
    } catch (error) {
        console.error('Ошибка при загрузке метрик:', error);
    }
    
    // Загружаем метрики по сервисам
    try {
        const servicesResponse = await fetch('/api/v1/admin/services/list');
        const servicesData = await servicesResponse.json();
        
        if (servicesData.success) {
            updateServicesMetrics(servicesData.services);
        }
    } catch (error) {
        console.error('Ошибка при загрузке метрик сервисов:', error);
    }
}

function updateMetricsWidgets(metrics) {
    const perf = metrics.performance || {};
    const res = metrics.resources || {};
    
    // Общие метрики
    document.getElementById('totalRequests').textContent = formatNumber(perf.total_requests || 0);
    document.getElementById('totalErrors').textContent = formatNumber(perf.total_errors || 0);
    
    // Throughput (берем максимальное значение)
    const throughput = perf.throughput || {};
    const maxThroughput = Math.max(...Object.values(throughput), 0);
    document.getElementById('throughput').textContent = maxThroughput.toFixed(2);
    
    // Активные запросы
    const activeRequests = perf.active_requests || {};
    const totalActive = Object.values(activeRequests).reduce((sum, val) => sum + (val || 0), 0);
    document.getElementById('activeRequests').textContent = totalActive;
    
    // Ресурсы
    const cpuPercent = res.cpu_usage_percent || 0;
    const cpuProgress = document.getElementById('cpuProgress');
    cpuProgress.style.width = cpuPercent + '%';
    cpuProgress.textContent = cpuPercent.toFixed(1) + '%';
    cpuProgress.className = 'progress-bar ' + (cpuPercent > 80 ? 'bg-danger' : cpuPercent > 60 ? 'bg-warning' : 'bg-success');
    
    const memoryPercent = res.memory_usage_percent || 0;
    const memoryProgress = document.getElementById('memoryProgress');
    memoryProgress.style.width = memoryPercent + '%';
    memoryProgress.textContent = memoryPercent.toFixed(1) + '%';
    memoryProgress.className = 'progress-bar bg-warning ' + (memoryPercent > 80 ? 'bg-danger' : 'bg-warning');
}

function updateServicesMetrics(services) {
    const container = document.getElementById('servicesMetricsContainer');
    
    if (!services || Object.keys(services).length === 0) {
        container.innerHTML = '<div class="alert alert-info">Сервисы не найдены</div>';
        return;
    }
    
    let html = '<div class="table-responsive"><table class="table table-hover">';
    html += '<thead><tr><th>Сервис</th><th>Endpoints</th><th>Версия</th><th>Окружение</th><th>Статус</th><th>Действия</th></tr></thead><tbody>';
    
    Object.entries(services).forEach(([name, service]) => {
        const totalEndpoints = service.total_endpoints || 0;
        const metadata = service.metadata || {};
        const version = metadata.version || 'unknown';
        const environment = metadata.environment || 'production';
        
        // Определяем статус (если есть здоровые endpoints)
        let status = 'unknown';
        let statusBadge = '<span class="badge bg-secondary">Неизвестно</span>';
        
        if (service.endpoints && service.endpoints.length > 0) {
            const healthyCount = service.endpoints.filter(ep => ep.health && ep.health.status === 'healthy').length;
            if (healthyCount > 0) {
                status = 'healthy';
                statusBadge = `<span class="badge bg-success">Здоров (${healthyCount}/${totalEndpoints})</span>`;
            } else {
                status = 'unhealthy';
                statusBadge = '<span class="badge bg-danger">Не здоров</span>';
            }
        }
        
        html += `<tr>
            <td><strong>${escapeHtml(name)}</strong></td>
            <td>${totalEndpoints}</td>
            <td>${escapeHtml(version)}</td>
            <td><span class="badge bg-info">${escapeHtml(environment)}</span></td>
            <td>${statusBadge}</td>
            <td>
                <a href="/admin/services?service=${encodeURIComponent(name)}" class="btn btn-sm btn-primary">
                    <i class="bi bi-eye"></i> Детали
                </a>
            </td>
        </tr>`;
    });
    
    html += '</tbody></table></div>';
    container.innerHTML = html;
}

function formatNumber(num) {
    if (num >= 1000000) {
        return (num / 1000000).toFixed(1) + 'M';
    } else if (num >= 1000) {
        return (num / 1000).toFixed(1) + 'K';
    }
    return num.toString();
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// Автоматическое обновление
document.addEventListener('DOMContentLoaded', function() {
    refreshMetrics();
    
    // Обновление каждые 5 секунд
    metricsInterval = setInterval(refreshMetrics, 5000);
});

// Остановка обновления при уходе со страницы
window.addEventListener('beforeunload', function() {
    if (metricsInterval) {
        clearInterval(metricsInterval);
    }
});
