/**
 * Управление модулями (FR-056, FR-064).
 */
let modulesData = [];
let searchTimeout = null;

document.addEventListener('DOMContentLoaded', function() {
    refreshModules();
    const searchEl = document.getElementById('moduleSearch');
    if (searchEl) {
        searchEl.addEventListener('input', function() {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(refreshModules, 300);
        });
    }
    ['typeFilter', 'enabledFilter', 'compatibleFilter', 'requiredFilter'].forEach(function(id) {
        const el = document.getElementById(id);
        if (el) el.addEventListener('change', refreshModules);
    });
    setInterval(refreshModules, 30000);
});

function getModulesApiUrl() {
    const params = new URLSearchParams();
    const includeAvailable = document.getElementById('includeAvailable');
    if (includeAvailable && includeAvailable.checked) params.set('include_available', 'true');
    const search = document.getElementById('moduleSearch');
    if (search && search.value.trim()) params.set('search', search.value.trim());
    const type = document.getElementById('typeFilter');
    if (type && type.value) params.set('type', type.value);
    const enabled = document.getElementById('enabledFilter');
    if (enabled && enabled.value) params.set('enabled', enabled.value);
    const compatible = document.getElementById('compatibleFilter');
    if (compatible && compatible.value) params.set('compatible', compatible.value);
    const required = document.getElementById('requiredFilter');
    if (required && required.value) params.set('required', required.value);
    const qs = params.toString();
    return '/api/v1/admin/modules' + (qs ? '?' + qs : '');
}

async function refreshModules() {
    const container = document.getElementById('modulesContainer');
    try {
        const url = getModulesApiUrl();
        const response = await fetch(url);
        const data = await response.json();
        if (data.success) {
            modulesData = Object.entries(data.modules || {}).map(([name, info]) => ({
                name: name,
                ...info
            }));
            renderModules();
        } else {
            container.innerHTML = '<div class="alert alert-danger">Ошибка загрузки модулей: ' + (data.error || 'Неизвестная ошибка') + '</div>';
        }
    } catch (error) {
        container.innerHTML = '<div class="alert alert-danger">Ошибка при загрузке модулей: ' + error.message + '</div>';
    }
}

function getCompatibilityBadge(mod) {
    const comp = mod.compatibility;
    if (!comp) return '<span class="badge bg-secondary">—</span>';
    if (comp.is_compatible === true) return '<span class="badge bg-success">Совместим</span>';
    return '<span class="badge bg-danger" title="' + escapeHtml(comp.error || '') + '">Не совместим</span>';
}

function renderModules() {
    const container = document.getElementById('modulesContainer');
    if (modulesData.length === 0) {
        container.innerHTML = '<div class="alert alert-info">Модули не найдены. Включите «Показать доступные», чтобы увидеть незагруженные модули.</div>';
        return;
    }
    const typeLabels = {
        db_driver: 'Драйвер БД',
        sd_provider: 'Service Discovery',
        protocol: 'Протокол',
        integration: 'Интеграция',
        auth: 'Аутентификация',
        security: 'Безопасность',
        functional: 'Функциональный',
        crm: 'CRM'
    };
    let html = '<div class="table-responsive"><table class="admin-table table table-hover table-sm">';
    html += '<thead><tr><th>Имя</th><th>Тип</th><th>Версия</th><th>Описание</th><th>Статус</th><th>Совместимость</th><th>Обязательный</th><th>Действия</th></tr></thead><tbody>';
    modulesData.forEach(mod => {
        const typeLabel = typeLabels[mod.type] || mod.type || '—';
        const isAvailable = mod.status === 'available' || mod.is_loaded === false;
        let statusBadge;
        if (isAvailable) {
            statusBadge = '<span class="badge bg-info">Доступен</span>';
        } else {
            statusBadge = mod.is_enabled
                ? '<span class="badge bg-success">Включён</span>'
                : '<span class="badge bg-secondary">Отключён</span>';
        }
        const requiredBadge = mod.is_required
            ? '<span class="badge bg-warning text-dark">Да</span>'
            : '<span class="badge bg-light text-dark">Нет</span>';
        const compBadge = getCompatibilityBadge(mod);
        let actions = '';
        if (!isAvailable) {
            if (mod.is_enabled && !mod.is_required) {
                actions += '<button class="btn btn-warning btn-sm" onclick="disableModule(\'' + escapeHtml(mod.name) + '\')" title="Отключить"><i class="bi bi-pause"></i></button> ';
            } else if (!mod.is_enabled) {
                actions += '<button class="btn btn-success btn-sm" onclick="enableModule(\'' + escapeHtml(mod.name) + '\')" title="Включить"><i class="bi bi-play"></i></button> ';
            }
        }
        actions += '<button class="btn btn-outline-secondary btn-sm" onclick="showModuleInfo(\'' + escapeHtml(mod.name) + '\')" title="Подробнее"><i class="bi bi-info-circle"></i></button>';
        html += '<tr>';
        html += '<td><strong>' + escapeHtml(mod.name) + '</strong></td>';
        html += '<td>' + escapeHtml(typeLabel) + '</td>';
        html += '<td>' + escapeHtml(mod.version || '—') + '</td>';
        html += '<td><small>' + escapeHtml((mod.description || '').slice(0, 50)) + ((mod.description || '').length > 50 ? '…' : '') + '</small></td>';
        html += '<td>' + statusBadge + '</td>';
        html += '<td>' + compBadge + '</td>';
        html += '<td>' + requiredBadge + '</td>';
        html += '<td>' + actions + '</td></tr>';
    });
    html += '</tbody></table></div>';
    container.innerHTML = html;
}

async function showModuleInfo(moduleName) {
    document.getElementById('infoModuleName').textContent = moduleName;
    const container = document.getElementById('moduleInfoContainer');
    container.innerHTML = '<div class="text-center"><div class="spinner-border text-primary"></div></div>';
    const modal = new bootstrap.Modal(document.getElementById('infoModal'));
    modal.show();
    try {
        const response = await fetch('/api/v1/admin/modules/' + encodeURIComponent(moduleName) + '/info');
        const data = await response.json();
        if (data.success) {
            const m = data.module;
            let body = '<dl class="row mb-0">';
            body += '<dt class="col-sm-4">Версия</dt><dd class="col-sm-8">' + escapeHtml(m.version || '—') + '</dd>';
            body += '<dt class="col-sm-4">Тип</dt><dd class="col-sm-8">' + escapeHtml(m.type || '—') + '</dd>';
            body += '<dt class="col-sm-4">Описание</dt><dd class="col-sm-8">' + escapeHtml(m.description || '—') + '</dd>';
            body += '<dt class="col-sm-4">Автор</dt><dd class="col-sm-8">' + escapeHtml(m.author || '—') + '</dd>';
            body += '<dt class="col-sm-4">Загружен</dt><dd class="col-sm-8">' + (m.is_loaded ? 'Да' : 'Нет') + '</dd>';
            body += '<dt class="col-sm-4">Включён</dt><dd class="col-sm-8">' + (m.is_enabled ? 'Да' : 'Нет') + '</dd>';
            body += '<dt class="col-sm-4">Обязательный</dt><dd class="col-sm-8">' + (m.is_required ? 'Да' : 'Нет') + '</dd>';
            if (m.compatibility) {
                body += '<dt class="col-sm-4">Совместимость</dt><dd class="col-sm-8">' + getCompatibilityBadge(m) + (m.compatibility.error ? ' <small class="text-muted">' + escapeHtml(m.compatibility.error) + '</small>' : '') + '</dd>';
            }
            if ((m.dependencies || []).length) {
                body += '<dt class="col-sm-4">Зависимости</dt><dd class="col-sm-8">' + escapeHtml(m.dependencies.join(', ')) + '</dd>';
            }
            if ((m.containers || []).length) {
                body += '<dt class="col-sm-4">Контейнеры</dt><dd class="col-sm-8"><ul class="list-unstyled mb-0">';
                m.containers.forEach(function(c) {
                    body += '<li><code>' + escapeHtml(c.name || c.id || JSON.stringify(c)) + '</code></li>';
                });
                body += '</ul></dd>';
            }
            body += '</dl>';
            container.innerHTML = body;
        } else {
            container.innerHTML = '<div class="alert alert-danger">' + escapeHtml(data.error || 'Не удалось загрузить информацию') + '</div>';
        }
    } catch (error) {
        container.innerHTML = '<div class="alert alert-danger">' + escapeHtml(error.message) + '</div>';
    }
}

async function enableModule(name) {
    try {
        const response = await fetch('/api/v1/admin/modules/' + encodeURIComponent(name) + '/enable', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' }
        });
        const data = await response.json();
        if (data.success) {
            refreshModules();
        } else {
            alert('Ошибка: ' + (data.error || 'Неизвестная ошибка'));
        }
    } catch (e) {
        alert('Ошибка: ' + e.message);
    }
}

async function disableModule(name) {
    if (!confirm('Отключить модуль "' + name + '"?')) return;
    try {
        const response = await fetch('/api/v1/admin/modules/' + encodeURIComponent(name) + '/disable', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' }
        });
        const data = await response.json();
        if (data.success) {
            refreshModules();
        } else {
            alert('Ошибка: ' + (data.error || 'Неизвестная ошибка'));
        }
    } catch (e) {
        alert('Ошибка: ' + e.message);
    }
}

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