<!--
  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 %}Audit Log - Familiar Admin{% endblock %}

{% block head %}
<style>
    .severity-debug { color: #6b7280; }
    .severity-info { color: #3b82f6; }
    .severity-warning { color: #f59e0b; }
    .severity-error { color: #ef4444; }
    .severity-critical { color: #dc2626; font-weight: bold; }
</style>
{% 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">Audit Log</h1>
            <p class="text-gray-500">Security and compliance event tracking</p>
        </div>
        <div class="flex space-x-2">
            <a href="{{ url_for('admin.audit_export', format='csv', days=days) }}" 
               class="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700">
                📥 Export CSV
            </a>
            <a href="{{ url_for('admin.audit_export', format='json', days=days) }}" 
               class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                📥 Export JSON
            </a>
            <button onclick="verifyChain()" 
                    class="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700">
                🔒 Verify Chain
            </button>
        </div>
    </div>
    
    <!-- Stats Cards -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-8">
        <div class="bg-white rounded-lg shadow p-4">
            <div class="text-sm text-gray-500">Total Events</div>
            <div class="text-2xl font-bold text-gray-800">{{ stats.total_events | default(0) }}</div>
        </div>
        <div class="bg-white rounded-lg shadow p-4">
            <div class="text-sm text-gray-500">Security Events</div>
            <div class="text-2xl font-bold text-red-600">{{ stats.security_events | default(0) }}</div>
        </div>
        <div class="bg-white rounded-lg shadow p-4">
            <div class="text-sm text-gray-500">Unique Actors</div>
            <div class="text-2xl font-bold text-blue-600">{{ stats.by_actor | length }}</div>
        </div>
        <div class="bg-white rounded-lg shadow p-4">
            <div class="text-sm text-gray-500">Time Period</div>
            <div class="text-2xl font-bold text-gray-800">{{ days }} days</div>
        </div>
    </div>
    
    <!-- Filters -->
    <div class="bg-white rounded-lg shadow p-4 mb-6">
        <form method="GET" class="flex flex-wrap gap-4 items-end">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Time Range</label>
                <select name="days" class="px-3 py-2 border rounded-lg">
                    <option value="1" {% if days == 1 %}selected{% endif %}>Last 24 hours</option>
                    <option value="7" {% if days == 7 %}selected{% endif %}>Last 7 days</option>
                    <option value="30" {% if days == 30 %}selected{% endif %}>Last 30 days</option>
                    <option value="90" {% if days == 90 %}selected{% endif %}>Last 90 days</option>
                </select>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Action</label>
                <select name="action" class="px-3 py-2 border rounded-lg">
                    <option value="">All Actions</option>
                    {% for action in actions %}
                    <option value="{{ action }}" {% if request.args.get('action') == action %}selected{% endif %}>
                        {{ action }}
                    </option>
                    {% endfor %}
                </select>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Actor</label>
                <input type="text" name="actor" value="{{ request.args.get('actor', '') }}"
                       placeholder="Email..."
                       class="px-3 py-2 border rounded-lg">
            </div>
            <button type="submit" class="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700">
                Filter
            </button>
        </form>
    </div>
    
    <!-- Events Table -->
    <div class="bg-white rounded-lg shadow overflow-hidden">
        <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
                <tr>
                    <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Time</th>
                    <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Actor</th>
                    <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Action</th>
                    <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Resource</th>
                    <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">IP</th>
                    <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Details</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-gray-200">
                {% for event in events %}
                <tr class="hover:bg-gray-50">
                    <td class="px-4 py-3 text-sm text-gray-500 whitespace-nowrap">
                        {{ event.timestamp.strftime('%Y-%m-%d %H:%M:%S') }}
                    </td>
                    <td class="px-4 py-3 text-sm">
                        {% if event.actor_email %}
                        <span class="text-gray-800">{{ event.actor_email }}</span>
                        {% else %}
                        <span class="text-gray-400">{{ event.actor_id or 'system' }}</span>
                        {% endif %}
                    </td>
                    <td class="px-4 py-3 text-sm">
                        <span class="severity-{{ event.severity.value if event.severity else 'info' }}">
                            {{ event.action.value if event.action else '-' }}
                        </span>
                    </td>
                    <td class="px-4 py-3 text-sm text-gray-600">
                        {% if event.resource_type %}
                        {{ event.resource_type }}{% if event.resource_id %}:{{ event.resource_id[:12] }}{% endif %}
                        {% else %}-{% endif %}
                    </td>
                    <td class="px-4 py-3 text-sm text-gray-500 font-mono">
                        {{ event.ip_address or '-' }}
                    </td>
                    <td class="px-4 py-3 text-sm">
                        {% if event.details %}
                        <button onclick="showDetails('{{ event.id }}')" 
                                class="text-purple-600 hover:text-purple-800">
                            View
                        </button>
                        <div id="details-{{ event.id }}" class="hidden mt-2 p-2 bg-gray-100 rounded text-xs font-mono">
                            {{ event.details | tojson }}
                        </div>
                        {% else %}-{% endif %}
                    </td>
                </tr>
                {% else %}
                <tr>
                    <td colspan="6" class="px-4 py-8 text-center text-gray-500">
                        No audit events found
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>
    
    <!-- Pagination info -->
    <div class="mt-4 text-sm text-gray-500 text-center">
        Showing {{ events | length }} events (max 500)
    </div>
</div>

<!-- Verification Modal -->
<div id="verifyModal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
    <div class="bg-white rounded-lg shadow-xl p-6 max-w-md w-full mx-4">
        <h3 class="text-lg font-bold mb-4">Chain Verification</h3>
        <div id="verifyResult" class="text-sm">
            Verifying...
        </div>
        <button onclick="document.getElementById('verifyModal').classList.add('hidden')"
                class="mt-4 px-4 py-2 bg-gray-200 rounded hover:bg-gray-300">
            Close
        </button>
    </div>
</div>

<script>
function showDetails(eventId) {
    const el = document.getElementById('details-' + eventId);
    el.classList.toggle('hidden');
}

async function verifyChain() {
    const modal = document.getElementById('verifyModal');
    const result = document.getElementById('verifyResult');
    
    modal.classList.remove('hidden');
    result.innerHTML = '<div class="animate-pulse">Verifying hash chain...</div>';
    
    try {
        const response = await fetch('{{ url_for("admin.audit_verify") }}', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'}
        });
        const data = await response.json();
        
        if (data.verified) {
            result.innerHTML = `
                <div class="text-green-600 font-bold mb-2">✅ Chain Verified</div>
                <div class="text-gray-600">
                    Events checked: ${data.events_checked}<br>
                    No tampering detected.
                </div>
            `;
        } else {
            result.innerHTML = `
                <div class="text-red-600 font-bold mb-2">❌ Chain Broken</div>
                <div class="text-gray-600">
                    Events checked: ${data.events_checked}<br>
                    Broken links: ${data.broken_links.length}
                </div>
            `;
        }
    } catch (error) {
        result.innerHTML = `<div class="text-red-600">Error: ${error.message}</div>`;
    }
}
</script>
{% endblock %}
