<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>System Update - GO-ACS</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="/static/css/style.css">
</head>

<body>
    <!-- Sidebar loaded via sidebar.js -->
    <script src="/static/js/sidebar.js"></script>

    <main class="main-content">
        <div class="header">
            <div>
                <h1>System Update</h1>
                <p style="color: var(--gray); margin-top: 0.5rem;">Update GO-ACS from GitHub repository</p>
            </div>
            <div class="header-actions">
                <button class="btn btn-primary" onclick="checkForUpdates()" id="checkBtn">
                    <i class="fas fa-sync-alt"></i>
                    Check for Updates
                </button>
            </div>
        </div>

        <!-- Current Version Info -->
        <div class="card" style="margin-bottom: 1.5rem;">
            <div class="card-header">
                <h2 class="card-title"><i class="fas fa-info-circle"></i> Current Version</h2>
            </div>
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 1.5rem;">
                <div>
                    <div style="color: var(--gray); font-size: 0.875rem; margin-bottom: 0.5rem;">Version</div>
                    <div id="currentVersion" style="font-size: 1.25rem; font-weight: 600; color: var(--primary);">v1.0.0
                    </div>
                </div>
                <div>
                    <div style="color: var(--gray); font-size: 0.875rem; margin-bottom: 0.5rem;">Last Update</div>
                    <div id="lastUpdate" style="font-size: 1rem; font-weight: 500;">-</div>
                </div>
                <div>
                    <div style="color: var(--gray); font-size: 0.875rem; margin-bottom: 0.5rem;">Current Branch</div>
                    <div id="currentBranch" style="font-size: 1rem; font-weight: 500;">-</div>
                </div>
                <div>
                    <div style="color: var(--gray); font-size: 0.875rem; margin-bottom: 0.5rem;">Status</div>
                    <div id="updateStatus" style="font-size: 1rem; font-weight: 500;">
                        <span class="status-badge" style="background: rgba(16, 185, 129, 0.1); color: #10b981;">
                            <i class="fas fa-check-circle"></i> Up to date
                        </span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Update Actions -->
        <div class="card" style="margin-bottom: 1.5rem;">
            <div class="card-header">
                <h2 class="card-title"><i class="fas fa-download"></i> Update Actions</h2>
            </div>
            <div style="display: flex; flex-direction: column; gap: 1rem;">
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem;">
                    <button class="btn btn-primary" onclick="performUpdate()" id="updateBtn" disabled>
                        <i class="fas fa-cloud-download-alt"></i>
                        Pull Latest Changes
                    </button>
                    <button class="btn btn-secondary" onclick="rebuildApp()" id="rebuildBtn">
                        <i class="fas fa-hammer"></i>
                        Rebuild Application
                    </button>
                    <button class="btn btn-secondary" onclick="restartService()" id="restartBtn">
                        <i class="fas fa-redo"></i>
                        Restart Service
                    </button>
                </div>
                <div
                    style="background: rgba(245, 158, 11, 0.1); border-left: 3px solid #f59e0b; padding: 1rem; border-radius: 8px;">
                    <div style="display: flex; align-items: start; gap: 0.75rem;">
                        <i class="fas fa-exclamation-triangle" style="color: #f59e0b; margin-top: 2px;"></i>
                        <div>
                            <div style="font-weight: 600; margin-bottom: 0.25rem;">Important:</div>
                            <div style="font-size: 0.875rem; color: var(--gray);">
                                This will pull the latest changes from GitHub, rebuild the application, and restart the
                                service.
                                The service will be unavailable for a few moments during the update process.
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Update Log Terminal -->
        <div class="card">
            <div class="card-header">
                <h2 class="card-title"><i class="fas fa-terminal"></i> Update Log</h2>
                <button class="btn btn-secondary" style="padding: 6px 12px; font-size: 0.75rem;" onclick="clearLog()">
                    <i class="fas fa-eraser"></i> Clear
                </button>
            </div>
            <div id="updateLog" class="terminal-output">
                <div class="log-line">Ready to check for updates...</div>
            </div>
        </div>
    </main>

    <style>
        .status-badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 0.875rem;
            font-weight: 500;
        }

        .terminal-output {
            background: #0f0d24;
            border: 1px solid var(--border);
            border-radius: 8px;
            padding: 1rem;
            min-height: 300px;
            max-height: 500px;
            overflow-y: auto;
            font-family: 'Courier New', monospace;
            font-size: 0.875rem;
            line-height: 1.6;
        }

        .log-line {
            color: #e2e8f0;
            margin-bottom: 0.25rem;
        }

        .log-line.success {
            color: #10b981;
        }

        .log-line.error {
            color: #ef4444;
        }

        .log-line.warning {
            color: #f59e0b;
        }

        .log-line.info {
            color: #0ea5e9;
        }

        .log-line.command {
            color: #a78bfa;
            font-weight: 600;
        }

        .btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .btn:disabled:hover {
            transform: none;
            box-shadow: none;
        }
    </style>

    <script>
        function addLog(message, type = '') {
            const logContainer = document.getElementById('updateLog');
            const logLine = document.createElement('div');
            logLine.className = `log-line ${type}`;
            logLine.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
            logContainer.appendChild(logLine);
            logContainer.scrollTop = logContainer.scrollHeight;
        }

        function clearLog() {
            document.getElementById('updateLog').innerHTML = '<div class="log-line">Log cleared.</div>';
        }

        async function checkForUpdates() {
            const btn = document.getElementById('checkBtn');
            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Checking...';

            addLog('Checking for updates...', 'info');

            try {
                const response = await fetch('/api/update/check');
                if (!response.ok) throw new Error('Failed to check for updates');

                const data = await response.json();

                // Update version info
                document.getElementById('currentVersion').textContent = data.current_version || 'v1.0.0';
                document.getElementById('currentBranch').textContent = data.current_branch || 'main';
                document.getElementById('lastUpdate').textContent = data.last_update || 'Unknown';

                if (data.updates_available) {
                    addLog(`✓ Updates available! ${data.commits_behind} commits behind`, 'success');
                    addLog(data.latest_commit_message, '');

                    document.getElementById('updateStatus').innerHTML = `
                        <span class="status-badge" style="background: rgba(245, 158, 11, 0.1); color: #f59e0b;">
                            <i class="fas fa-arrow-up"></i> Updates Available
                        </span>
                    `;
                    document.getElementById('updateBtn').disabled = false;
                } else {
                    addLog('✓ Already up to date', 'success');

                    document.getElementById('updateStatus').innerHTML = `
                        <span class="status-badge" style="background: rgba(16, 185, 129, 0.1); color: #10b981;">
                            <i class="fas fa-check-circle"></i> Up to date
                        </span>
                    `;
                    document.getElementById('updateBtn').disabled = true;
                }
            } catch (error) {
                console.error('Error checking updates:', error);
                addLog(`✗ Error: ${error.message}`, 'error');
            } finally {
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-sync-alt"></i> Check for Updates';
            }
        }

        async function performUpdate() {
            if (!confirm('This will update the application and restart the service. Continue?')) {
                return;
            }

            const btn = document.getElementById('updateBtn');
            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Updating...';

            addLog('Starting update process...', 'command');

            try {
                const response = await fetch('/api/update/perform', {
                    method: 'POST'
                });

                if (!response.ok) throw new Error('Update failed');

                const reader = response.body.getReader();
                const decoder = new TextDecoder();

                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;

                    const text = decoder.decode(value);
                    const lines = text.split('\n').filter(line => line.trim());

                    lines.forEach(line => {
                        try {
                            const data = JSON.parse(line);
                            addLog(data.message, data.type || '');
                        } catch {
                            addLog(line, '');
                        }
                    });
                }

                addLog('✓ Update completed! Service will restart...', 'success');

                setTimeout(() => {
                    addLog('Checking service status...', 'info');
                    location.reload();
                }, 5000);

            } catch (error) {
                console.error('Error performing update:', error);
                addLog(`✗ Error: ${error.message}`, 'error');
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-cloud-download-alt"></i> Pull Latest Changes';
            }
        }

        async function rebuildApp() {
            if (!confirm('This will rebuild the application. Continue?')) {
                return;
            }

            const btn = document.getElementById('rebuildBtn');
            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Building...';

            addLog('Starting rebuild...', 'command');

            try {
                const response = await fetch('/api/update/rebuild', {
                    method: 'POST'
                });

                if (!response.ok) throw new Error('Rebuild failed');

                const reader = response.body.getReader();
                const decoder = new TextDecoder();

                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;

                    const text = decoder.decode(value);
                    const lines = text.split('\n').filter(line => line.trim());

                    lines.forEach(line => {
                        try {
                            const data = JSON.parse(line);
                            addLog(data.message, data.type || '');
                        } catch {
                            addLog(line, '');
                        }
                    });
                }

                addLog('✓ Rebuild completed!', 'success');

            } catch (error) {
                console.error('Error rebuilding:', error);
                addLog(`✗ Error: ${error.message}`, 'error');
            } finally {
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-hammer"></i> Rebuild Application';
            }
        }

        async function restartService() {
            if (!confirm('This will restart the GO-ACS service. Continue?')) {
                return;
            }

            const btn = document.getElementById('restartBtn');
            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Restarting...';

            addLog('Restarting service...', 'command');

            try {
                const response = await fetch('/api/update/restart', {
                    method: 'POST'
                });

                if (!response.ok) throw new Error('Restart failed');

                addLog('✓ Service restart initiated...', 'success');

                setTimeout(() => {
                    addLog('Checking service status...', 'info');
                    location.reload();
                }, 5000);

            } catch (error) {
                console.error('Error restarting:', error);
                addLog(`✗ Error: ${error.message}`, 'error');
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-redo"></i> Restart Service';
            }
        }

        // Initialize
        document.addEventListener('DOMContentLoaded', () => {
            addLog('Update manager ready', 'success');
        });
    </script>
</body>

</html>