<!--
  Familiar - Self-hosted AI Agent
  Copyright (c) 2026 George Scott Foley
  
  Licensed under the MIT License
  For commercial licensing, contact: licensing@familiar.ai
-->
{% extends "base.html" %}

{% block title %}System Status - Familiar Admin{% endblock %}

{% block content %}
<div class="max-w-7xl mx-auto px-4 py-8">
    <!-- Header -->
    <div class="flex justify-between items-center mb-8">
        <div>
            <h1 class="text-2xl font-bold text-gray-800">System Status</h1>
            <p class="text-gray-500">High availability and health monitoring</p>
        </div>
        <button onclick="refreshStatus()" 
                class="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700">
            🔄 Refresh
        </button>
    </div>
    
    <!-- Health Status -->
    <div class="bg-white rounded-lg shadow p-6 mb-6">
        <h2 class="text-lg font-semibold mb-4">Health Status</h2>
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div class="text-center p-4 rounded-lg {% if health.healthy %}bg-green-100{% else %}bg-red-100{% endif %}">
                <div class="text-4xl mb-2">
                    {% if health.healthy %}✅{% else %}❌{% endif %}
                </div>
                <div class="font-semibold {% if health.healthy %}text-green-700{% else %}text-red-700{% endif %}">
                    {{ health.status | upper }}
                </div>
            </div>
            
            <div class="bg-gray-50 p-4 rounded-lg">
                <div class="text-sm text-gray-500">Uptime</div>
                <div class="text-xl font-bold">{{ "%.1f"|format(health.uptime_seconds / 3600) }} hrs</div>
            </div>
            
            <div class="bg-gray-50 p-4 rounded-lg">
                <div class="text-sm text-gray-500">Requests/min</div>
                <div class="text-xl font-bold">{{ "%.1f"|format(health.requests_per_minute) }}</div>
            </div>
            
            <div class="bg-gray-50 p-4 rounded-lg">
                <div class="text-sm text-gray-500">Error Rate</div>
                <div class="text-xl font-bold {% if health.error_rate > 0.05 %}text-red-600{% endif %}">
                    {{ "%.1f"|format(health.error_rate * 100) }}%
                </div>
            </div>
        </div>
        
        <!-- Component Health -->
        <div class="mt-6">
            <h3 class="font-medium mb-3">Component Health</h3>
            <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
                <div class="flex items-center space-x-2 p-2 bg-gray-50 rounded">
                    <span class="{% if health.redis_connected %}text-green-500{% else %}text-gray-400{% endif %}">●</span>
                    <span>Redis</span>
                </div>
                <div class="flex items-center space-x-2 p-2 bg-gray-50 rounded">
                    <span class="{% if health.database_connected %}text-green-500{% else %}text-red-500{% endif %}">●</span>
                    <span>Database</span>
                </div>
                <div class="flex items-center space-x-2 p-2 bg-gray-50 rounded">
                    <span class="{% if health.llm_available %}text-green-500{% else %}text-red-500{% endif %}">●</span>
                    <span>LLM Provider</span>
                </div>
                {% for name, ok in health.checks.items() %}
                <div class="flex items-center space-x-2 p-2 bg-gray-50 rounded">
                    <span class="{% if ok %}text-green-500{% else %}text-red-500{% endif %}">●</span>
                    <span>{{ name | title }}</span>
                </div>
                {% endfor %}
            </div>
        </div>
    </div>
    
    <!-- HA Cluster Status -->
    {% if ha_enabled %}
    <div class="bg-white rounded-lg shadow p-6 mb-6">
        <h2 class="text-lg font-semibold mb-4">Cluster Status</h2>
        
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
            <div class="bg-gray-50 p-4 rounded-lg">
                <div class="text-sm text-gray-500">Mode</div>
                <div class="text-xl font-bold">{{ ha_mode | title }}</div>
            </div>
            <div class="bg-gray-50 p-4 rounded-lg">
                <div class="text-sm text-gray-500">This Node</div>
                <div class="text-xl font-bold 
                    {% if node_state == 'active' %}text-green-600
                    {% elif node_state == 'standby' %}text-yellow-600
                    {% else %}text-gray-600{% endif %}">
                    {{ node_state | upper }}
                </div>
            </div>
            <div class="bg-gray-50 p-4 rounded-lg">
                <div class="text-sm text-gray-500">Active Nodes</div>
                <div class="text-xl font-bold">{{ active_nodes }} / {{ cluster_size }}</div>
            </div>
        </div>
        
        <!-- Node List -->
        <h3 class="font-medium mb-3">Cluster Nodes</h3>
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Node ID</th>
                        <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Hostname</th>
                        <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">State</th>
                        <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Last Heartbeat</th>
                        <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200">
                    {% for node in nodes %}
                    <tr class="{% if node.node_id == current_node %}bg-purple-50{% endif %}">
                        <td class="px-4 py-2 text-sm font-mono">
                            {{ node.node_id[:16] }}...
                            {% if node.node_id == current_node %}
                            <span class="ml-2 text-xs bg-purple-200 text-purple-800 px-1 rounded">this</span>
                            {% endif %}
                            {% if node.node_id == leader %}
                            <span class="ml-2 text-xs bg-green-200 text-green-800 px-1 rounded">leader</span>
                            {% endif %}
                        </td>
                        <td class="px-4 py-2 text-sm">{{ node.hostname }}</td>
                        <td class="px-4 py-2 text-sm">
                            <span class="px-2 py-1 rounded text-xs
                                {% if node.state == 'active' %}bg-green-100 text-green-800
                                {% elif node.state == 'standby' %}bg-yellow-100 text-yellow-800
                                {% elif node.state == 'draining' %}bg-orange-100 text-orange-800
                                {% else %}bg-red-100 text-red-800{% endif %}">
                                {{ node.state }}
                            </span>
                        </td>
                        <td class="px-4 py-2 text-sm text-gray-500">
                            {{ node.last_heartbeat.strftime('%H:%M:%S') if node.last_heartbeat else '-' }}
                        </td>
                        <td class="px-4 py-2 text-sm">
                            {% if node.node_id == current_node %}
                            <button onclick="drainNode()" 
                                    class="text-orange-600 hover:text-orange-800 text-xs">
                                Drain
                            </button>
                            {% endif %}
                        </td>
                    </tr>
                    {% else %}
                    <tr>
                        <td colspan="5" class="px-4 py-4 text-center text-gray-500">
                            No cluster nodes (standalone mode)
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
    {% else %}
    <div class="bg-white rounded-lg shadow p-6 mb-6">
        <h2 class="text-lg font-semibold mb-4">High Availability</h2>
        <div class="text-center py-8">
            <div class="text-4xl mb-4">🔌</div>
            <p class="text-gray-600 mb-4">High availability is not enabled.</p>
            <p class="text-sm text-gray-500">
                Enable HA by setting <code class="bg-gray-100 px-1 rounded">HA_ENABLED=true</code> 
                and configuring Redis.
            </p>
        </div>
    </div>
    {% endif %}
    
    <!-- Backups -->
    <div class="bg-white rounded-lg shadow p-6">
        <div class="flex justify-between items-center mb-4">
            <h2 class="text-lg font-semibold">Recent Backups</h2>
            <a href="{{ url_for('admin.backup_create') }}" 
               class="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 text-sm">
                + Create Backup
            </a>
        </div>
        
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">ID</th>
                        <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Type</th>
                        <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
                        <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Size</th>
                        <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Created</th>
                        <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200">
                    {% for backup in backups[:5] %}
                    <tr>
                        <td class="px-4 py-2 text-sm font-mono">{{ backup.id }}</td>
                        <td class="px-4 py-2 text-sm">{{ backup.backup_type.value }}</td>
                        <td class="px-4 py-2 text-sm">
                            <span class="px-2 py-1 rounded text-xs
                                {% if backup.status.value == 'completed' %}bg-green-100 text-green-800
                                {% elif backup.status.value == 'failed' %}bg-red-100 text-red-800
                                {% else %}bg-gray-100 text-gray-800{% endif %}">
                                {{ backup.status.value }}
                            </span>
                        </td>
                        <td class="px-4 py-2 text-sm">
                            {{ "%.1f"|format(backup.total_size / 1024) }} KB
                        </td>
                        <td class="px-4 py-2 text-sm text-gray-500">
                            {{ backup.created_at.strftime('%Y-%m-%d %H:%M') }}
                        </td>
                        <td class="px-4 py-2 text-sm space-x-2">
                            <a href="{{ url_for('admin.backup_download', backup_id=backup.id) }}" 
                               class="text-purple-600 hover:text-purple-800">Download</a>
                            <button onclick="restoreBackup('{{ backup.id }}')"
                                    class="text-orange-600 hover:text-orange-800">Restore</button>
                        </td>
                    </tr>
                    {% else %}
                    <tr>
                        <td colspan="6" class="px-4 py-8 text-center text-gray-500">
                            No backups yet. Create one to enable disaster recovery.
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
function refreshStatus() {
    location.reload();
}

async function drainNode() {
    if (!confirm('Drain this node? It will stop accepting new requests.')) return;
    
    try {
        const response = await fetch('/ha/drain', { method: 'POST' });
        const data = await response.json();
        alert('Node draining: ' + data.status);
        location.reload();
    } catch (error) {
        alert('Error: ' + error.message);
    }
}

async function restoreBackup(backupId) {
    if (!confirm('Restore from backup ' + backupId + '? This will overwrite current data.')) return;
    
    try {
        const response = await fetch('/admin/backup/' + backupId + '/restore', { method: 'POST' });
        const data = await response.json();
        alert('Restore complete: ' + data.files_restored + ' files restored');
        location.reload();
    } catch (error) {
        alert('Error: ' + error.message);
    }
}

// Auto-refresh every 30 seconds
setInterval(refreshStatus, 30000);
</script>
{% endblock %}
