<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Governance Audit Dashboard</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            background: #f5f7fa;
            color: #333;
            line-height: 1.6;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }

        header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 10px;
            margin-bottom: 30px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }

        h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }

        .subtitle {
            opacity: 0.9;
            font-size: 1.1em;
        }

        .filters {
            background: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 30px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            display: flex;
            gap: 20px;
            align-items: center;
            flex-wrap: wrap;
        }

        .filter-group {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        label {
            font-weight: 600;
            color: #555;
        }

        select, button {
            padding: 10px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 6px;
            font-size: 14px;
            transition: all 0.3s;
        }

        select:hover, select:focus {
            border-color: #667eea;
            outline: none;
        }

        button {
            background: #667eea;
            color: white;
            border: none;
            cursor: pointer;
            font-weight: 600;
        }

        button:hover {
            background: #5568d3;
            transform: translateY(-1px);
            box-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            padding: 25px;
            border-radius: 10px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            transition: transform 0.3s;
        }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        }

        .stat-label {
            color: #888;
            font-size: 0.9em;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-bottom: 10px;
        }

        .stat-value {
            font-size: 2.5em;
            font-weight: bold;
            color: #667eea;
        }

        .stat-card.cost .stat-value {
            color: #f59e0b;
        }

        .stat-card.success .stat-value {
            color: #10b981;
        }

        .stat-card.blocked .stat-value {
            color: #ef4444;
        }

        .charts-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .chart-card {
            background: white;
            padding: 25px;
            border-radius: 10px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .chart-title {
            font-size: 1.3em;
            font-weight: 600;
            margin-bottom: 20px;
            color: #444;
        }

        .chart-container {
            position: relative;
            height: 300px;
        }

        .logs-section {
            background: white;
            padding: 25px;
            border-radius: 10px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .section-title {
            font-size: 1.5em;
            font-weight: 600;
            margin-bottom: 20px;
            color: #444;
        }

        .logs-table {
            width: 100%;
            border-collapse: collapse;
        }

        .logs-table th {
            background: #f9fafb;
            padding: 12px;
            text-align: left;
            font-weight: 600;
            color: #555;
            border-bottom: 2px solid #e5e7eb;
        }

        .logs-table td {
            padding: 12px;
            border-bottom: 1px solid #e5e7eb;
        }

        .logs-table tr:hover {
            background: #f9fafb;
            cursor: pointer;
        }

        .status-badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.85em;
            font-weight: 600;
        }

        .status-success {
            background: #d1fae5;
            color: #065f46;
        }

        .status-blocked {
            background: #fee2e2;
            color: #991b1b;
        }

        .status-error {
            background: #fef3c7;
            color: #92400e;
        }

        .status-allowed {
            background: #dbeafe;
            color: #1e40af;
        }

        .code-preview {
            font-family: 'Monaco', 'Menlo', 'Courier New', monospace;
            font-size: 0.85em;
            background: #f3f4f6;
            padding: 8px;
            border-radius: 4px;
            max-width: 400px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 1000;
            overflow: auto;
        }

        .modal-content {
            background: white;
            margin: 50px auto;
            padding: 30px;
            border-radius: 10px;
            max-width: 1200px;
            box-shadow: 0 10px 25px rgba(0,0,0,0.3);
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #e5e7eb;
        }

        .close {
            font-size: 2em;
            color: #999;
            cursor: pointer;
            transition: color 0.3s;
        }

        .close:hover {
            color: #333;
        }

        .modal-section {
            margin-bottom: 25px;
        }

        .modal-section h3 {
            color: #667eea;
            margin-bottom: 10px;
            font-size: 1.2em;
        }

        .code-block {
            background: #1e293b;
            color: #e2e8f0;
            padding: 20px;
            border-radius: 8px;
            overflow-x: auto;
            font-family: 'Monaco', 'Menlo', 'Courier New', monospace;
            font-size: 0.9em;
            line-height: 1.5;
            max-height: 400px;
        }

        .code-diff {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
        }

        .diff-section {
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            overflow: hidden;
        }

        .diff-header {
            background: #f9fafb;
            padding: 10px 15px;
            font-weight: 600;
            border-bottom: 1px solid #e5e7eb;
        }

        .diff-header.original {
            color: #dc2626;
        }

        .diff-header.refactored {
            color: #16a34a;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #888;
        }

        .no-data {
            text-align: center;
            padding: 40px;
            color: #888;
            font-style: italic;
        }

        .pagination {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px solid #e5e7eb;
        }

        .pagination-info {
            color: #666;
            font-size: 0.9em;
        }

        .pagination-controls {
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .pagination-btn {
            padding: 8px 16px;
            border: 2px solid #e0e0e0;
            border-radius: 6px;
            background: white;
            color: #333;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            transition: all 0.3s;
        }

        .pagination-btn:hover:not(:disabled) {
            border-color: #667eea;
            color: #667eea;
            transform: translateY(-1px);
        }

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

        .pagination-btn.active {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }

        .page-number {
            padding: 8px 12px;
            border: 2px solid #e0e0e0;
            border-radius: 6px;
            background: white;
            color: #333;
            font-size: 14px;
            font-weight: 600;
            min-width: 40px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
        }

        .page-number:hover {
            border-color: #667eea;
            color: #667eea;
        }

        .page-number.active {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }

        .per-page-selector {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .per-page-selector select {
            padding: 6px 10px;
            font-size: 13px;
        }

        @media (max-width: 768px) {
            .charts-grid {
                grid-template-columns: 1fr;
            }

            .code-diff {
                grid-template-columns: 1fr;
            }

            .filters {
                flex-direction: column;
                align-items: stretch;
            }

            .filter-group {
                flex-direction: column;
                align-items: stretch;
            }

            .pagination {
                flex-direction: column;
                gap: 15px;
            }

            .pagination-controls {
                flex-wrap: wrap;
                justify-content: center;
            }

            .pagination-btn {
                padding: 6px 12px;
                font-size: 12px;
            }

            .page-number {
                padding: 6px 10px;
                font-size: 12px;
                min-width: 35px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>AI Governance Audit Dashboard</h1>
            <div class="subtitle">Monitor and analyze your AI-assisted refactoring activities</div>
        </header>

        <div class="filters">
            <div class="filter-group">
                <label for="timeframe">Timeframe:</label>
                <select id="timeframe" onchange="loadData()">
                    <option value="day">Last 24 Hours</option>
                    <option value="week" selected>Last Week</option>
                    <option value="month">Last Month</option>
                    <option value="all">All Time</option>
                </select>
            </div>
            <div class="filter-group">
                <label for="statusFilter">Status:</label>
                <select id="statusFilter" onchange="loadData()">
                    <option value="">All Statuses</option>
                    <option value="success">Success</option>
                    <option value="blocked">Blocked</option>
                    <option value="error">Error</option>
                    <option value="allowed">Allowed</option>
                </select>
            </div>
            <button onclick="loadData()">Refresh</button>
        </div>

        <div class="stats-grid" id="statsGrid">
            <div class="stat-card">
                <div class="stat-label">Total Requests</div>
                <div class="stat-value" id="totalRequests">-</div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Total Tokens</div>
                <div class="stat-value" id="totalTokens">-</div>
            </div>
            <div class="stat-card cost">
                <div class="stat-label">Total Cost</div>
                <div class="stat-value" id="totalCost">-</div>
            </div>
            <div class="stat-card success">
                <div class="stat-label">Successful</div>
                <div class="stat-value" id="successCount">-</div>
            </div>
        </div>

        <div class="charts-grid">
            <div class="chart-card">
                <div class="chart-title">Cost Over Time</div>
                <div class="chart-container">
                    <canvas id="costChart"></canvas>
                </div>
            </div>
            <div class="chart-card">
                <div class="chart-title">Token Usage Over Time</div>
                <div class="chart-container">
                    <canvas id="tokensChart"></canvas>
                </div>
            </div>
        </div>

        <div class="logs-section">
            <div class="section-title">Recent Audit Logs</div>
            <div id="logsContainer">
                <div class="loading">Loading audit logs...</div>
            </div>
        </div>
    </div>

    <!-- Modal for log details -->
    <div id="logModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Audit Log Details</h2>
                <span class="close" onclick="closeModal()">&times;</span>
            </div>
            <div id="modalBody">
                <!-- Populated dynamically -->
            </div>
        </div>
    </div>

    <script>
        let costChart = null;
        let tokensChart = null;
        let currentPage = 1;
        let perPage = 20;
        let paginationData = null;

        // Load initial data
        document.addEventListener('DOMContentLoaded', () => {
            loadData();
        });

        async function loadData(resetPage = true) {
            const timeframe = document.getElementById('timeframe').value;
            const statusFilter = document.getElementById('statusFilter').value;

            // Reset to page 1 when filters change
            if (resetPage) {
                currentPage = 1;
            }

            try {
                // Load statistics
                await loadStatistics(timeframe);

                // Load charts
                await loadCharts(timeframe);

                // Load logs table
                await loadLogs(timeframe, statusFilter);
            } catch (error) {
                console.error('Error loading data:', error);
            }
        }

        async function loadStatistics(timeframe) {
            const response = await fetch(`/api/statistics?timeframe=${timeframe}`);
            const data = await response.json();

            if (data.success) {
                const stats = data.statistics;
                document.getElementById('totalRequests').textContent = stats.total_requests.toLocaleString();
                document.getElementById('totalTokens').textContent = stats.total_tokens.toLocaleString();
                document.getElementById('totalCost').textContent = '$' + stats.total_cost.toFixed(4);
                document.getElementById('successCount').textContent = (stats.status_counts.success || 0).toLocaleString();
            }
        }

        async function loadCharts(timeframe) {
            const response = await fetch(`/api/cost-over-time?timeframe=${timeframe}`);
            const data = await response.json();

            if (data.success && data.data.length > 0) {
                const labels = data.data.map(d => d.date);
                const costs = data.data.map(d => d.cost);
                const tokens = data.data.map(d => d.tokens);

                // Cost chart
                if (costChart) {
                    costChart.destroy();
                }
                const costCtx = document.getElementById('costChart').getContext('2d');
                costChart = new Chart(costCtx, {
                    type: 'line',
                    data: {
                        labels: labels,
                        datasets: [{
                            label: 'Cost (USD)',
                            data: costs,
                            borderColor: '#f59e0b',
                            backgroundColor: 'rgba(245, 158, 11, 0.1)',
                            tension: 0.4,
                            fill: true
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: false
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                ticks: {
                                    callback: function(value) {
                                        return '$' + value.toFixed(4);
                                    }
                                }
                            }
                        }
                    }
                });

                // Tokens chart
                if (tokensChart) {
                    tokensChart.destroy();
                }
                const tokensCtx = document.getElementById('tokensChart').getContext('2d');
                tokensChart = new Chart(tokensCtx, {
                    type: 'bar',
                    data: {
                        labels: labels,
                        datasets: [{
                            label: 'Tokens Used',
                            data: tokens,
                            borderColor: '#667eea',
                            backgroundColor: 'rgba(102, 126, 234, 0.7)',
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: false
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                ticks: {
                                    callback: function(value) {
                                        return value.toLocaleString();
                                    }
                                }
                            }
                        }
                    }
                });
            }
        }

        async function loadLogs(timeframe, status) {
            const params = new URLSearchParams({
                timeframe,
                page: currentPage,
                per_page: perPage
            });
            if (status) {
                params.append('status', status);
            }

            const response = await fetch(`/api/logs?${params}`);
            const data = await response.json();

            const container = document.getElementById('logsContainer');

            if (data.success && data.logs.length > 0) {
                paginationData = data.pagination;

                const table = `
                    <table class="logs-table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Timestamp</th>
                                <th>File</th>
                                <th>Action</th>
                                <th>Status</th>
                                <th>Tokens</th>
                                <th>Cost</th>
                                <th>Target</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${data.logs.map(log => `
                                <tr onclick="showLogDetail(${log.id})">
                                    <td>${log.id}</td>
                                    <td>${new Date(log.timestamp).toLocaleString()}</td>
                                    <td><code>${log.filepath.split('/').pop()}</code></td>
                                    <td>${log.action}</td>
                                    <td><span class="status-badge status-${log.status}">${log.status}</span></td>
                                    <td>${log.tokens_used || 0}</td>
                                    <td>$${(log.cost || 0).toFixed(6)}</td>
                                    <td>${log.target_description || '-'}</td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                    ${renderPagination()}
                `;
                container.innerHTML = table;
            } else {
                container.innerHTML = '<div class="no-data">No audit logs found for the selected timeframe.</div>';
            }
        }

        function renderPagination() {
            if (!paginationData || paginationData.total_pages <= 1) {
                return '';
            }

            const { page, total_logs, total_pages, has_previous, has_next } = paginationData;
            const startRecord = (page - 1) * perPage + 1;
            const endRecord = Math.min(page * perPage, total_logs);

            // Generate page numbers to display
            let pageNumbers = [];
            const maxPagesToShow = 5;
            let startPage = Math.max(1, page - Math.floor(maxPagesToShow / 2));
            let endPage = Math.min(total_pages, startPage + maxPagesToShow - 1);

            // Adjust startPage if we're near the end
            if (endPage - startPage < maxPagesToShow - 1) {
                startPage = Math.max(1, endPage - maxPagesToShow + 1);
            }

            for (let i = startPage; i <= endPage; i++) {
                pageNumbers.push(i);
            }

            return `
                <div class="pagination">
                    <div class="pagination-info">
                        Showing ${startRecord}-${endRecord} of ${total_logs} logs
                    </div>

                    <div class="pagination-controls">
                        <div class="per-page-selector">
                            <label>Show:</label>
                            <select onchange="changePerPage(this.value)">
                                <option value="10" ${perPage === 10 ? 'selected' : ''}>10</option>
                                <option value="20" ${perPage === 20 ? 'selected' : ''}>20</option>
                                <option value="50" ${perPage === 50 ? 'selected' : ''}>50</option>
                                <option value="100" ${perPage === 100 ? 'selected' : ''}>100</option>
                            </select>
                        </div>

                        <button class="pagination-btn"
                                onclick="changePage(1)"
                                ${!has_previous ? 'disabled' : ''}>
                            ⟨⟨ First
                        </button>

                        <button class="pagination-btn"
                                onclick="changePage(${page - 1})"
                                ${!has_previous ? 'disabled' : ''}>
                            ⟨ Previous
                        </button>

                        ${pageNumbers.map(p => `
                            <div class="page-number ${p === page ? 'active' : ''}"
                                 onclick="changePage(${p})">
                                ${p}
                            </div>
                        `).join('')}

                        <button class="pagination-btn"
                                onclick="changePage(${page + 1})"
                                ${!has_next ? 'disabled' : ''}>
                            Next ⟩
                        </button>

                        <button class="pagination-btn"
                                onclick="changePage(${total_pages})"
                                ${!has_next ? 'disabled' : ''}>
                            Last ⟩⟩
                        </button>
                    </div>
                </div>
            `;
        }

        function changePage(newPage) {
            currentPage = newPage;
            loadData(false); // Don't reset page when navigating
        }

        function changePerPage(newPerPage) {
            perPage = parseInt(newPerPage);
            currentPage = 1; // Reset to first page when changing per page
            loadData(false); // Don't reset page (already set to 1)
        }

        async function showLogDetail(logId) {
            const response = await fetch(`/api/log/${logId}`);
            const data = await response.json();

            if (data.success) {
                const log = data.log;
                const modalBody = document.getElementById('modalBody');

                let html = `
                    <div class="modal-section">
                        <h3>Basic Information</h3>
                        <p><strong>ID:</strong> ${log.id}</p>
                        <p><strong>Timestamp:</strong> ${new Date(log.timestamp).toLocaleString()}</p>
                        <p><strong>File:</strong> ${log.filepath}</p>
                        <p><strong>Action:</strong> ${log.action}</p>
                        <p><strong>Status:</strong> <span class="status-badge status-${log.status}">${log.status}</span></p>
                        <p><strong>Reason:</strong> ${log.reason || 'N/A'}</p>
                    </div>

                    <div class="modal-section">
                        <h3>Usage & Cost</h3>
                        <p><strong>Model:</strong> ${log.model || 'N/A'}</p>
                        <p><strong>Tokens Used:</strong> ${(log.tokens_used || 0).toLocaleString()}</p>
                        <p><strong>Cost:</strong> $${(log.cost || 0).toFixed(6)}</p>
                        <p><strong>Target Description:</strong> ${log.target_description || 'N/A'}</p>
                    </div>
                `;

                if (log.findings) {
                    html += `
                        <div class="modal-section">
                            <h3>Security Findings</h3>
                            <p>${log.findings}</p>
                        </div>
                    `;
                }

                if (log.original_code && log.refactored_code) {
                    html += `
                        <div class="modal-section">
                            <h3>Code Changes</h3>
                            <div class="code-diff">
                                <div class="diff-section">
                                    <div class="diff-header original">Original Code</div>
                                    <pre class="code-block">${escapeHtml(log.original_code)}</pre>
                                </div>
                                <div class="diff-section">
                                    <div class="diff-header refactored">Refactored Code</div>
                                    <pre class="code-block">${escapeHtml(log.refactored_code)}</pre>
                                </div>
                            </div>
                        </div>
                    `;
                } else if (log.original_code) {
                    html += `
                        <div class="modal-section">
                            <h3>Original Code</h3>
                            <pre class="code-block">${escapeHtml(log.original_code)}</pre>
                        </div>
                    `;
                }

                modalBody.innerHTML = html;
                document.getElementById('logModal').style.display = 'block';
            }
        }

        function closeModal() {
            document.getElementById('logModal').style.display = 'none';
        }

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

        // Close modal when clicking outside
        window.onclick = function(event) {
            const modal = document.getElementById('logModal');
            if (event.target == modal) {
                closeModal();
            }
        }
    </script>
</body>
</html>
