// DeployHub Main Interactivity Script

function openModal(id) {
    const el = document.getElementById(id);
    if (el) el.classList.add('active');
}

function closeModal(id) {
    const el = document.getElementById(id);
    if (el) el.classList.remove('active');
}

let deployTimerInterval = null;
let deploySecondsElapsed = 0;

function startDeployChronometer() {
    deploySecondsElapsed = 0;
    const chronometerEl = document.getElementById('deploy-chronometer');
    if (chronometerEl) chronometerEl.innerText = '00:00s';

    if (deployTimerInterval) clearInterval(deployTimerInterval);

    deployTimerInterval = setInterval(() => {
        deploySecondsElapsed++;
        const mins = String(Math.floor(deploySecondsElapsed / 60)).padStart(2, '0');
        const secs = String(deploySecondsElapsed % 60).padStart(2, '0');
        if (chronometerEl) {
            chronometerEl.innerText = `${mins}:${secs}s`;
        }
    }, 1000);
}

function stopDeployChronometer() {
    if (deployTimerInterval) {
        clearInterval(deployTimerInterval);
        deployTimerInterval = null;
    }
}

function updateDeployProgress(pct, stepLabel = "") {
    const progressBar = document.getElementById('deploy-progress-bar');
    const pctText = document.getElementById('deploy-pct-text');
    const statusText = document.getElementById('deploy-status-text');

    const cleanPct = Math.min(100, Math.max(0, Math.round(pct)));

    if (progressBar) progressBar.style.width = `${cleanPct}%`;
    if (pctText) pctText.innerText = `${cleanPct}%`;
    if (statusText && stepLabel) statusText.innerText = stepLabel;
}

async function runDeepScan(serverId) {
    const btn = document.getElementById('btn-deep-scan');
    if (btn) {
        btn.disabled = true;
        btn.innerHTML = `
            <svg class="animate-spin" width="18" height="18" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg>
            <span>ESCANEAR VPS (SSH)...</span>
        `;
    }

    try {
        const res = await fetch(`/server/${serverId}/deep-scan`, { method: 'POST' });
        const data = await res.json();
        if (res.ok && data.status === 'success') {
            window.location.reload();
        } else {
            alert(`Falha no escaneamento: ${data.error || 'Erro desconhecido'}`);
        }
    } catch (e) {
        alert(`Erro de comunicação com o servidor: ${e.message}`);
    } finally {
        if (btn) {
            btn.disabled = false;
            btn.innerHTML = `
                <svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg>
                <span>ESCANEAR VPS AGORA</span>
            `;
        }
    }
}

function handleDeploySubmit(event, appId) {
    event.preventDefault();
    closeModal('modal-upload-deploy');
    openModal('modal-deploy-progress');

    const form = event.target;
    const formData = new FormData(form);
    const term = document.getElementById('deploy-terminal');

    startDeployChronometer();
    updateDeployProgress(2, 'Passo 1/11: Transmitindo arquivo ZIP para o servidor...');

    if (term) term.innerHTML = '<div class="terminal-line">[INFO] Transmitindo arquivo ZIP via socket HTTP...</div>';

    const xhr = new XMLHttpRequest();
    xhr.open('POST', `/app/${appId}/deploy`, true);

    let lastProgressPct = -1;

    xhr.upload.onprogress = function(e) {
        if (e.lengthComputable) {
            const loadedMb = (e.loaded / (1024 * 1024)).toFixed(1);
            const totalMb = (e.total / (1024 * 1024)).toFixed(1);
            const rawUploadPct = Math.round((e.loaded / e.total) * 100);
            
            // Map upload phase 0-100% to progress bar 2% - 30%
            const barPct = 2 + Math.round((e.loaded / e.total) * 28);
            
            updateDeployProgress(barPct, `Passo 1/11: Enviando ZIP (${loadedMb} MB de ${totalMb} MB - ${rawUploadPct}%)...`);

            if (rawUploadPct >= lastProgressPct + 20) {
                lastProgressPct = rawUploadPct;
                if (term) {
                    term.innerHTML += `<div class="terminal-line">[INFO] Progresso do Upload do ZIP: ${loadedMb} MB / ${totalMb} MB (${rawUploadPct}%)</div>`;
                    term.scrollTop = term.scrollHeight;
                }
            }
        }
    };

    xhr.onload = function() {
        stopDeployChronometer();
        let data;
        try {
            data = JSON.parse(xhr.responseText);
        } catch (err) {
            data = { status: 'failed', error: `Servidor respondeu HTTP ${xhr.status}: ${xhr.responseText.slice(0, 300)}` };
        }

        if (term && data.logs) {
            term.innerHTML = data.logs.map(l => {
                let cls = 'terminal-line';
                if (l.includes('[SUCCESS]')) cls += ' text-success';
                if (l.includes('[ERROR]')) cls += ' text-danger';
                if (l.includes('[WARN]')) cls += ' text-warning';
                
                if (l.includes('Passo 2/11')) updateDeployProgress(35, 'Passo 2/11: Conectando SSH...');
                if (l.includes('Passo 3/11')) updateDeployProgress(45, 'Passo 3/11: Enviando SFTP para Staging...');
                if (l.includes('Passo 4/11')) updateDeployProgress(55, 'Passo 4/11: Inspecionando AST WSGI...');
                if (l.includes('Passo 5/11')) updateDeployProgress(65, 'Passo 5/11: Backup & Cópia em Produção...');
                if (l.includes('Passo 6/11')) updateDeployProgress(75, 'Passo 6/11: Compilando Venv & Dependências...');
                if (l.includes('Passo 7/11')) updateDeployProgress(85, 'Passo 7/11: Criando Serviço Systemd...');
                if (l.includes('Passo 8/11')) updateDeployProgress(90, 'Passo 8/11: Liberando Firewall...');
                if (l.includes('Passo 9/11')) updateDeployProgress(93, 'Passo 9/11: Reiniciando Daemon Systemd...');
                if (l.includes('Passo 10/11')) updateDeployProgress(96, 'Passo 10/11: Verificação 5 Camadas de Saúde...');
                if (l.includes('Passo 11/11')) updateDeployProgress(100, 'Passo 11/11: Registrando Release Imutável...');

                return `<div class="${cls}">${l}</div>`;
            }).join('');
            term.scrollTop = term.scrollHeight;
        }

        if (xhr.status === 200 && data.status === 'success') {
            updateDeployProgress(100, '🎉 DEPLOY REAL CONCLUÍDO COM SUCESSO!');
            const mins = String(Math.floor(deploySecondsElapsed / 60)).padStart(2, '0');
            const secs = String(deploySecondsElapsed % 60).padStart(2, '0');
            if (term) term.innerHTML += `<div class="terminal-line text-success">[SUCCESS] Tempo total de execução do deploy: ${mins}:${secs}s</div>`;
            setTimeout(() => { window.location.reload(); }, 2500);
        } else {
            updateDeployProgress(0, `❌ DEPLOY FALHOU (${data.error || 'Erro no servidor'})`);
            if (term && data.error && !data.logs) {
                term.innerHTML += `<div class="terminal-line text-danger">[ERROR] ${data.error}</div>`;
            }
        }
    };

    xhr.onerror = function() {
        stopDeployChronometer();
        if (term) {
            term.innerHTML += `<div class="terminal-line text-danger">[ERROR] Conexão resetada pelo servidor (net::ERR_CONNECTION_RESET). O upload estourou o tempo limite ou a transmissão foi interrompida.</div>`;
            term.innerHTML += `<div class="terminal-line text-warning">[DICA] Tente enviar um arquivo ZIP reduzido (sem venv ou node_modules).</div>`;
        }
        updateDeployProgress(0, '❌ FALHA NA TRANSMISSÃO HTTP DO UPLOAD');
    };

    xhr.send(formData);
}

async function executeRollback(appId, deploymentId, versionLabel) {
    if (!confirm(`Deseja restaurar a aplicação para a ${versionLabel}?`)) {
        return;
    }

    try {
        const res = await fetch(`/app/${appId}/rollback/${deploymentId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        });

        const contentType = res.headers.get("content-type") || "";
        let data;
        if (contentType.includes("application/json")) {
            data = await res.json();
        } else {
            const rawText = await res.text();
            throw new Error(`HTTP ${res.status}: ${rawText.slice(0, 300)}`);
        }

        if (!res.ok || data.success === false) {
            throw new Error(data.error || `HTTP ${res.status}`);
        }

        alert(data.message || 'Rollback executado com sucesso!');
        window.location.reload();

    } catch (err) {
        alert(`Rollback falhou: ${err.message}`);
    }
}

async function triggerDbBackup(appId) {
    try {
        const res = await fetch(`/app/${appId}/backup-db`, { method: 'POST' });
        const data = await res.json();
        if (res.ok && data.status === 'success') {
            alert(`Backup concluído! Arquivo: ${data.backup.file_name} (${data.backup.size_mb} MB)`);
            window.location.reload();
        } else {
            alert(`Falha no backup: ${data.error || 'Erro desconhecido'}`);
        }
    } catch (e) {
        alert(`Erro de comunicação: ${e.message}`);
    }
}

function showPortDetails(port, protocol, bindIp, exposure, process, pid, cmdline, cwd, app) {
    const content = document.getElementById('port-modal-content');
    if (!content) return;

    content.innerHTML = `
        <h2 style="font-size: 22px; font-weight: 700; margin-bottom: 16px;">Detalhes da Porta :${port}</h2>
        <div class="terminal-window" style="font-size: 13px;">
            <div class="terminal-line"><span style="color: var(--primary);">Porta TCP/UDP:</span> :${port} (${protocol})</div>
            <div class="terminal-line"><span style="color: var(--primary);">Bind Address:</span> ${bindIp}:${port}</div>
            <div class="terminal-line"><span style="color: var(--primary);">Exposição de Rede:</span> ${exposure === 'public' ? '🌐 Pública (0.0.0.0)' : '🔒 Interna (127.0.0.1)'}</div>
            <div class="terminal-line"><span style="color: var(--primary);">Processo Ativo:</span> ${process} (PID: ${pid || 'Desconhecido'})</div>
            <div class="terminal-line"><span style="color: var(--primary);">Aplicação Mapeada:</span> ${app}</div>
            <div class="terminal-line"><span style="color: var(--primary);">Diretório de Trabalho:</span> ${cwd || 'N/A'}</div>
            <div class="terminal-line" style="margin-top: 8px;"><span style="color: var(--primary);">Linha de Comando Completa:</span></div>
            <div class="terminal-line" style="color: #93c5fd; word-break: break-all;">${cmdline || 'N/A'}</div>
        </div>
    `;
    openModal('modal-port-details');
}
