<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Health Status - MySQL to Sheets Sync</title>
    <style>
        :root {
            --primary: #2563eb;
            --primary-hover: #1d4ed8;
            --success: #16a34a;
            --error: #dc2626;
            --warning: #ca8a04;
            --bg: #f8fafc;
            --card-bg: #ffffff;
            --border: #e2e8f0;
            --text: #1e293b;
            --text-muted: #64748b;
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: var(--bg);
            color: var(--text);
            line-height: 1.5;
            padding: 2rem;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
        }

        h1 {
            font-size: 1.5rem;
            font-weight: 600;
        }

        .nav-links {
            display: flex;
            gap: 1rem;
        }

        .nav-links a {
            color: var(--primary);
            text-decoration: none;
            font-size: 0.875rem;
        }

        .nav-links a:hover {
            text-decoration: underline;
        }

        .version {
            color: var(--text-muted);
            font-size: 0.875rem;
        }

        .overall-status {
            text-align: center;
            padding: 2rem;
            margin-bottom: 2rem;
            border-radius: 0.5rem;
        }

        .overall-status.healthy {
            background: #f0fdf4;
            border: 1px solid #bbf7d0;
        }

        .overall-status.degraded {
            background: #fefce8;
            border: 1px solid #fef08a;
        }

        .overall-status.unhealthy {
            background: #fef2f2;
            border: 1px solid #fecaca;
        }

        .overall-status .status-icon {
            font-size: 3rem;
            margin-bottom: 0.5rem;
        }

        .overall-status .status-text {
            font-size: 1.5rem;
            font-weight: 600;
        }

        .overall-status .status-subtext {
            color: var(--text-muted);
            font-size: 0.875rem;
        }

        .components-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 1.5rem;
        }

        .component-card {
            background: var(--card-bg);
            border: 1px solid var(--border);
            border-radius: 0.5rem;
            padding: 1.5rem;
        }

        .component-card.healthy {
            border-left: 4px solid var(--success);
        }

        .component-card.error {
            border-left: 4px solid var(--error);
        }

        .component-card.warning {
            border-left: 4px solid var(--warning);
        }

        .component-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1rem;
        }

        .component-name {
            font-size: 1.125rem;
            font-weight: 600;
        }

        .component-status {
            display: inline-block;
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 500;
        }

        .component-status.healthy {
            background: #f0fdf4;
            color: var(--success);
        }

        .component-status.error {
            background: #fef2f2;
            color: var(--error);
        }

        .component-status.warning {
            background: #fefce8;
            color: var(--warning);
        }

        .component-details {
            font-size: 0.875rem;
            color: var(--text-muted);
        }

        .component-details dt {
            font-weight: 500;
            color: var(--text);
            margin-top: 0.5rem;
        }

        .component-details dd {
            margin-left: 0;
        }

        .component-error {
            background: #fef2f2;
            border-radius: 0.375rem;
            padding: 0.75rem;
            margin-top: 1rem;
            font-size: 0.875rem;
        }

        .component-error .error-code {
            font-family: monospace;
            background: white;
            padding: 0.125rem 0.375rem;
            border-radius: 0.25rem;
            font-size: 0.8125rem;
        }

        .remediation {
            background: #f0fdf4;
            border-left: 3px solid var(--success);
            padding: 0.75rem;
            margin-top: 0.5rem;
            font-size: 0.875rem;
        }

        .btn {
            display: inline-block;
            padding: 0.5rem 1rem;
            background: var(--primary);
            color: white;
            border: none;
            border-radius: 0.375rem;
            font-size: 0.875rem;
            cursor: pointer;
            text-decoration: none;
        }

        .btn:hover {
            background: var(--primary-hover);
        }

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

        .btn-secondary {
            background: var(--card-bg);
            color: var(--text);
            border: 1px solid var(--border);
        }

        .btn-secondary:hover {
            background: var(--bg);
        }

        .action-buttons {
            display: flex;
            gap: 0.5rem;
            margin-top: 1rem;
        }

        .system-info {
            margin-top: 2rem;
        }

        .system-info .card {
            background: var(--card-bg);
            border: 1px solid var(--border);
            border-radius: 0.5rem;
            padding: 1.5rem;
        }

        .system-info h2 {
            font-size: 1.125rem;
            font-weight: 600;
            margin-bottom: 1rem;
        }

        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
        }

        .info-item {
            padding: 0.75rem;
            background: var(--bg);
            border-radius: 0.375rem;
        }

        .info-item .label {
            font-size: 0.75rem;
            color: var(--text-muted);
            text-transform: uppercase;
        }

        .info-item .value {
            font-weight: 500;
        }

        .loading {
            text-align: center;
            padding: 2rem;
            color: var(--text-muted);
        }

        .last-checked {
            text-align: center;
            color: var(--text-muted);
            font-size: 0.875rem;
            margin-top: 1rem;
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <div>
                <h1>Health Status</h1>
                <span class="version">v{{ version }}</span>
            </div>
            <div class="nav-links">
                <a href="/">Dashboard</a>
                <a href="/errors">Error Log</a>
                <a href="/schedules">Schedules</a>
            </div>
        </header>

        <div id="loading" class="loading">Loading health status...</div>

        <div id="overall-status" class="overall-status" style="display: none;">
            <div class="status-icon" id="status-icon"></div>
            <div class="status-text" id="status-text"></div>
            <div class="status-subtext" id="status-subtext"></div>
        </div>

        <div class="components-grid" id="components-grid" style="display: none;">
            <!-- Database -->
            <div class="component-card" id="component-database">
                <div class="component-header">
                    <span class="component-name">Database</span>
                    <span class="component-status" id="db-status">-</span>
                </div>
                <dl class="component-details" id="db-details">
                    <dt>Status</dt>
                    <dd id="db-status-detail">Checking...</dd>
                </dl>
                <div class="component-error" id="db-error" style="display: none;"></div>
                <div class="action-buttons">
                    <button class="btn btn-secondary" onclick="testDatabase()">Test Connection</button>
                </div>
            </div>

            <!-- Google Sheets -->
            <div class="component-card" id="component-sheets">
                <div class="component-header">
                    <span class="component-name">Google Sheets</span>
                    <span class="component-status" id="sheets-status">-</span>
                </div>
                <dl class="component-details" id="sheets-details">
                    <dt>Status</dt>
                    <dd id="sheets-status-detail">Checking...</dd>
                </dl>
                <div class="component-error" id="sheets-error" style="display: none;"></div>
                <div class="action-buttons">
                    <button class="btn btn-secondary" onclick="testSheets()">Test Connection</button>
                </div>
            </div>

            <!-- Scheduler -->
            <div class="component-card" id="component-scheduler">
                <div class="component-header">
                    <span class="component-name">Scheduler</span>
                    <span class="component-status" id="scheduler-status">-</span>
                </div>
                <dl class="component-details" id="scheduler-details">
                    <dt>Status</dt>
                    <dd id="scheduler-status-detail">Checking...</dd>
                </dl>
            </div>

            <!-- System -->
            <div class="component-card" id="component-system">
                <div class="component-header">
                    <span class="component-name">System</span>
                    <span class="component-status" id="system-status">-</span>
                </div>
                <dl class="component-details" id="system-details">
                    <dt>Python</dt>
                    <dd id="system-python">-</dd>
                    <dt>Platform</dt>
                    <dd id="system-platform">-</dd>
                    <dt>Memory</dt>
                    <dd id="system-memory">-</dd>
                </dl>
            </div>
        </div>

        <div class="last-checked" id="last-checked" style="display: none;">
            Last checked: <span id="checked-at">-</span>
            <button class="btn btn-secondary" onclick="loadHealth(true)" style="margin-left: 1rem;">
                Refresh
            </button>
        </div>
    </div>

    <script>
        async function loadHealth(refresh = false) {
            document.getElementById('loading').style.display = 'block';
            document.getElementById('overall-status').style.display = 'none';
            document.getElementById('components-grid').style.display = 'none';
            document.getElementById('last-checked').style.display = 'none';

            try {
                const url = refresh ? '/api/health/status?refresh=true' : '/api/health/status';
                const response = await fetch(url);
                const data = await response.json();

                document.getElementById('loading').style.display = 'none';
                document.getElementById('overall-status').style.display = 'block';
                document.getElementById('components-grid').style.display = 'grid';
                document.getElementById('last-checked').style.display = 'block';

                renderOverallStatus(data.status);
                renderComponent('database', 'db', data.components.database);
                renderComponent('sheets', 'sheets', data.components.sheets);
                renderComponent('scheduler', 'scheduler', data.components.scheduler);
                renderSystemInfo(data.components.system);

                document.getElementById('checked-at').textContent = new Date(data.checked_at).toLocaleString();
            } catch (error) {
                console.error('Failed to load health:', error);
                document.getElementById('loading').textContent = 'Failed to load health status';
            }
        }

        function renderOverallStatus(status) {
            const container = document.getElementById('overall-status');
            const icon = document.getElementById('status-icon');
            const text = document.getElementById('status-text');
            const subtext = document.getElementById('status-subtext');

            container.className = 'overall-status ' + status;

            switch (status) {
                case 'healthy':
                    icon.textContent = '\u2713';
                    text.textContent = 'All Systems Healthy';
                    subtext.textContent = 'All components are operating normally';
                    break;
                case 'degraded':
                    icon.textContent = '\u26A0';
                    text.textContent = 'Degraded';
                    subtext.textContent = 'Some components have warnings';
                    break;
                case 'unhealthy':
                    icon.textContent = '\u2717';
                    text.textContent = 'Unhealthy';
                    subtext.textContent = 'One or more components have errors';
                    break;
            }
        }

        function renderComponent(cardId, prefix, data) {
            const card = document.getElementById('component-' + cardId);
            const statusBadge = document.getElementById(prefix + '-status');
            const statusDetail = document.getElementById(prefix + '-status-detail');
            const errorDiv = document.getElementById(prefix + '-error');

            // Set card class
            card.className = 'component-card ' + data.status;

            // Set status badge
            statusBadge.className = 'component-status ' + data.status;
            statusBadge.textContent = data.status.charAt(0).toUpperCase() + data.status.slice(1);

            // Set status detail
            if (data.status === 'healthy') {
                if (data.latency_ms) {
                    statusDetail.textContent = `Connected (${data.latency_ms}ms)`;
                } else {
                    statusDetail.textContent = 'OK';
                }
            } else {
                statusDetail.textContent = data.error || 'Error';
            }

            // Show error details if present
            if (errorDiv && data.error) {
                errorDiv.style.display = 'block';
                let errorHtml = `<strong>Error:</strong> ${escapeHtml(data.error)}`;
                if (data.error_code) {
                    errorHtml += `<br><strong>Code:</strong> <span class="error-code">${data.error_code}</span>`;
                }
                if (data.remediation) {
                    errorHtml += `<div class="remediation"><strong>Fix:</strong> ${escapeHtml(data.remediation)}</div>`;
                }
                errorDiv.innerHTML = errorHtml;
            } else if (errorDiv) {
                errorDiv.style.display = 'none';
            }

            // Add extra details for database
            if (cardId === 'database' && data.host) {
                const details = document.getElementById('db-details');
                details.innerHTML = `
                    <dt>Status</dt>
                    <dd id="db-status-detail">${statusDetail.textContent}</dd>
                    <dt>Type</dt>
                    <dd>${data.db_type || '-'}</dd>
                    <dt>Host</dt>
                    <dd>${data.host}:${data.port || '-'}</dd>
                    <dt>Database</dt>
                    <dd>${data.database || '-'}</dd>
                `;
            }

            // Add extra details for sheets
            if (cardId === 'sheets' && data.sheet_id) {
                const details = document.getElementById('sheets-details');
                details.innerHTML = `
                    <dt>Status</dt>
                    <dd id="sheets-status-detail">${statusDetail.textContent}</dd>
                    <dt>Sheet ID</dt>
                    <dd style="word-break: break-all; font-size: 0.8125rem;">${data.sheet_id}</dd>
                    <dt>Worksheet</dt>
                    <dd>${data.worksheet || 'Sheet1'}</dd>
                `;
            }
        }

        function renderSystemInfo(data) {
            document.getElementById('system-status').className = 'component-status healthy';
            document.getElementById('system-status').textContent = 'Healthy';
            document.getElementById('system-python').textContent = data.python_version || '-';
            document.getElementById('system-platform').textContent = `${data.platform || '-'} ${data.platform_version || ''}`.trim();
            document.getElementById('system-memory').textContent = data.memory_usage_mb ? `${data.memory_usage_mb} MB` : '-';
        }

        async function testDatabase() {
            const btn = event.target;
            btn.disabled = true;
            btn.textContent = 'Testing...';

            try {
                const response = await fetch('/api/health/database', { method: 'POST' });
                const data = await response.json();
                renderComponent('database', 'db', data);
            } catch (error) {
                console.error('Database test failed:', error);
            } finally {
                btn.disabled = false;
                btn.textContent = 'Test Connection';
            }
        }

        async function testSheets() {
            const btn = event.target;
            btn.disabled = true;
            btn.textContent = 'Testing...';

            try {
                const response = await fetch('/api/health/sheets', { method: 'POST' });
                const data = await response.json();
                renderComponent('sheets', 'sheets', data);
            } catch (error) {
                console.error('Sheets test failed:', error);
            } finally {
                btn.disabled = false;
                btn.textContent = 'Test Connection';
            }
        }

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

        // Initial load
        loadHealth();
    </script>
</body>
</html>
