<!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 - Enhanced</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: linear-gradient(135deg, #f5f7fa 0%, #e9ecef 100%);
            color: #333;
            line-height: 1.6;
        }

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

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

        h1 {
            font-size: 3em;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .subtitle {
            opacity: 0.95;
            font-size: 1.2em;
            margin-bottom: 20px;
        }

        .features-banner {
            background: rgba(255,255,255,0.2);
            padding: 15px 20px;
            border-radius: 10px;
            margin-top: 20px;
            display: flex;
            gap: 30px;
            flex-wrap: wrap;
        }

        .feature-item {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .feature-icon {
            font-size: 1.2em;
        }

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

        .tab {
            padding: 12px 24px;
            border: none;
            background: transparent;
            color: #666;
            font-weight: 600;
            cursor: pointer;
            border-radius: 8px;
            transition: all 0.3s;
        }

        .tab:hover {
            background: #f5f7fa;
            color: #667eea;
        }

        .tab.active {
            background: #667eea;
            color: white;
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

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

        .stat-card {
            background: white;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            transition: all 0.3s;
            position: relative;
            overflow: hidden;
        }

        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 4px;
            background: linear-gradient(90deg, #667eea, #764ba2);
        }

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

        .stat-icon {
            font-size: 2.5em;
            margin-bottom: 15px;
            opacity: 0.8;
        }

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

        .stat-value {
            font-size: 2.8em;
            font-weight: bold;
            color: #667eea;
            margin-bottom: 5px;
        }

        .stat-subvalue {
            font-size: 0.9em;
            color: #999;
        }

        .stat-card.cost .stat-value { color: #f59e0b; }
        .stat-card.success .stat-value { color: #10b981; }
        .stat-card.blocked .stat-value { color: #ef4444; }
        .stat-card.sessions .stat-value { color: #8b5cf6; }

        .section {
            background: white;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }

        .section-title {
            font-size: 1.8em;
            font-weight: 700;
            margin-bottom: 20px;
            color: #444;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .sessions-grid {
            display: grid;
            gap: 15px;
        }

        .session-card {
            background: #f9fafb;
            padding: 20px;
            border-radius: 10px;
            border-left: 4px solid #667eea;
            transition: all 0.3s;
            cursor: pointer;
        }

        .session-card:hover {
            background: #f3f4f6;
            transform: translateX(5px);
        }

        .session-card.completed {
            border-left-color: #10b981;
        }

        .session-card.in-progress {
            border-left-color: #f59e0b;
        }

        .session-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;
        }

        .session-id {
            font-family: 'Monaco', monospace;
            font-size: 0.9em;
            color: #667eea;
            font-weight: 600;
        }

        .session-status {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.8em;
            font-weight: 600;
        }

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

        .session-status.in-progress {
            background: #fed7aa;
            color: #92400e;
        }

        .progress-bar {
            width: 100%;
            height: 8px;
            background: #e5e7eb;
            border-radius: 4px;
            overflow: hidden;
            margin: 10px 0;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #667eea, #764ba2);
            transition: width 0.5s ease;
        }

        .session-meta {
            display: flex;
            gap: 20px;
            font-size: 0.9em;
            color: #666;
            margin-top: 10px;
        }

        .activity-timeline {
            position: relative;
            padding-left: 30px;
        }

        .activity-timeline::before {
            content: '';
            position: absolute;
            left: 8px;
            top: 0;
            bottom: 0;
            width: 2px;
            background: #e5e7eb;
        }

        .activity-item {
            position: relative;
            margin-bottom: 25px;
            padding: 15px;
            background: #f9fafb;
            border-radius: 8px;
            transition: all 0.3s;
        }

        .activity-item:hover {
            background: #f3f4f6;
            transform: translateX(5px);
        }

        .activity-item::before {
            content: '';
            position: absolute;
            left: -24px;
            top: 20px;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: white;
            border: 3px solid #667eea;
        }

        .activity-item.success::before { border-color: #10b981; }
        .activity-item.blocked::before { border-color: #ef4444; }
        .activity-item.error::before { border-color: #f59e0b; }

        .activity-time {
            font-size: 0.85em;
            color: #999;
            margin-bottom: 5px;
        }

        .activity-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .activity-file {
            font-family: 'Monaco', monospace;
            font-size: 0.9em;
            color: #667eea;
        }

        .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: 15px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }

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

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

        .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; }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #999;
        }

        .empty-state-icon {
            font-size: 4em;
            margin-bottom: 20px;
            opacity: 0.5;
        }

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

        .spinner {
            border: 4px solid #f3f4f6;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        @media (max-width: 768px) {
            h1 { font-size: 2em; }
            .stats-grid { grid-template-columns: 1fr; }
            .charts-grid { grid-template-columns: 1fr; }
            .features-banner { gap: 15px; }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>🛡️ AI Governance Audit Dashboard</h1>
            <div class="subtitle">Intelligent code refactoring with comprehensive monitoring & safety</div>
            <div class="features-banner">
                <div class="feature-item">
                    <span class="feature-icon">🔍</span>
                    <span>Call Graph Analysis</span>
                </div>
                <div class="feature-item">
                    <span class="feature-icon">🎯</span>
                    <span>Smart Context Selection</span>
                </div>
                <div class="feature-item">
                    <span class="feature-icon">📊</span>
                    <span>Impact Analysis</span>
                </div>
                <div class="feature-item">
                    <span class="feature-icon">✅</span>
                    <span>Test-Driven Validation</span>
                </div>
                <div class="feature-item">
                    <span class="feature-icon">💾</span>
                    <span>Checkpoint/Resume</span>
                </div>
                <div class="feature-item">
                    <span class="feature-icon">🚫</span>
                    <span>Blocked Files Handling</span>
                </div>
            </div>
        </header>

        <div class="tabs">
            <button class="tab active" onclick="switchTab('overview')">📈 Overview</button>
            <button class="tab" onclick="switchTab('sessions')">💾 Sessions</button>
            <button class="tab" onclick="switchTab('activity')">🕐 Recent Activity</button>
            <button class="tab" onclick="switchTab('logs')">📋 Audit Logs</button>
        </div>

        <!-- Overview Tab -->
        <div id="overview" class="tab-content active">
            <div class="stats-grid" id="statsGrid">
                <div class="stat-card">
                    <div class="stat-icon">📊</div>
                    <div class="stat-label">Total Refactorings</div>
                    <div class="stat-value" id="totalRequests">-</div>
                    <div class="stat-subvalue">All time operations</div>
                </div>
                <div class="stat-card success">
                    <div class="stat-icon">✅</div>
                    <div class="stat-label">Successful</div>
                    <div class="stat-value" id="successCount">-</div>
                    <div class="stat-subvalue">Files refactored</div>
                </div>
                <div class="stat-card blocked">
                    <div class="stat-icon">🚫</div>
                    <div class="stat-label">Blocked</div>
                    <div class="stat-value" id="blockedCount">-</div>
                    <div class="stat-subvalue">Security policy blocks</div>
                </div>
                <div class="stat-card cost">
                    <div class="stat-icon">💰</div>
                    <div class="stat-label">Total Cost</div>
                    <div class="stat-value" id="totalCost">-</div>
                    <div class="stat-subvalue"><span id="totalTokens">-</span> tokens used</div>
                </div>
                <div class="stat-card sessions">
                    <div class="stat-icon">💾</div>
                    <div class="stat-label">Active Sessions</div>
                    <div class="stat-value" id="activeSessions">-</div>
                    <div class="stat-subvalue"><span id="totalSessions">-</span> total sessions</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>

        <!-- Sessions Tab -->
        <div id="sessions" class="tab-content">
            <div class="section">
                <div class="section-title">💾 Refactoring Sessions</div>
                <div id="sessionsContainer">
                    <div class="loading">
                        <div class="spinner"></div>
                        Loading sessions...
                    </div>
                </div>
            </div>
        </div>

        <!-- Activity Tab -->
        <div id="activity" class="tab-content">
            <div class="section">
                <div class="section-title">🕐 Recent Activity</div>
                <div id="activityContainer">
                    <div class="loading">
                        <div class="spinner"></div>
                        Loading recent activity...
                    </div>
                </div>
            </div>
        </div>

        <!-- Logs Tab -->
        <div id="logs" class="tab-content">
            <div class="section">
                <div class="section-title">📋 Detailed Audit Logs</div>
                <div id="logsContainer">
                    <div class="loading">
                        <div class="spinner"></div>
                        Loading audit logs...
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let costChart = null;
        let tokensChart = null;

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

        async function loadData() {
            try {
                await loadEnhancedStatistics();
                await loadCharts();
                await loadSessions();
                await loadRecentActivity();
                await loadLogs();
            } catch (error) {
                console.error('Error loading data:', error);
            }
        }

        async function loadEnhancedStatistics() {
            const response = await fetch('/api/enhanced-statistics');
            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();
                document.getElementById('blockedCount').textContent = (stats.blocked_files || 0).toLocaleString();
                document.getElementById('activeSessions').textContent = (stats.sessions.active || 0).toLocaleString();
                document.getElementById('totalSessions').textContent = (stats.sessions.total || 0).toLocaleString();
            }
        }

        async function loadCharts() {
            const response = await fetch('/api/cost-over-time?timeframe=week');
            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,
                            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 loadSessions() {
            const response = await fetch('/api/sessions');
            const data = await response.json();

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

            if (data.success && data.sessions.length > 0) {
                const html = `
                    <div class="sessions-grid">
                        ${data.sessions.map(session => `
                            <div class="session-card ${session.percentage >= 100 ? 'completed' : 'in-progress'}">
                                <div class="session-header">
                                    <div class="session-id">${session.session_id}</div>
                                    <div class="session-status ${session.percentage >= 100 ? 'completed' : 'in-progress'}">
                                        ${session.percentage >= 100 ? 'COMPLETED' : 'IN PROGRESS'}
                                    </div>
                                </div>
                                <div><strong>Target:</strong> ${session.target}</div>
                                <div class="progress-bar">
                                    <div class="progress-fill" style="width: ${session.percentage}%"></div>
                                </div>
                                <div class="session-meta">
                                    <span>📅 ${new Date(session.timestamp).toLocaleDateString()}</span>
                                    <span>📊 ${session.progress}</span>
                                    ${session.failed > 0 ? `<span style="color: #ef4444">⚠️ ${session.failed} failed</span>` : ''}
                                </div>
                            </div>
                        `).join('')}
                    </div>
                `;
                container.innerHTML = html;
            } else {
                container.innerHTML = `
                    <div class="empty-state">
                        <div class="empty-state-icon">💾</div>
                        <h3>No Sessions Found</h3>
                        <p>Start a refactoring operation to see sessions here</p>
                    </div>
                `;
            }
        }

        async function loadRecentActivity() {
            const response = await fetch('/api/recent-activity');
            const data = await response.json();

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

            if (data.success) {
                const allActivity = [
                    ...data.activity.recent_refactors.map(a => ({...a, type: 'success'})),
                    ...data.activity.recent_blocks.map(a => ({...a, type: 'blocked'})),
                    ...data.activity.recent_errors.map(a => ({...a, type: 'error'}))
                ].sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));

                if (allActivity.length > 0) {
                    const html = `
                        <div class="activity-timeline">
                            ${allActivity.slice(0, 10).map(item => `
                                <div class="activity-item ${item.type}">
                                    <div class="activity-time">${new Date(item.timestamp).toLocaleString()}</div>
                                    <div class="activity-content">
                                        <div>
                                            <div class="activity-file">${item.filepath.split('/').pop()}</div>
                                            <div style="font-size: 0.9em; color: #666;">${item.action}</div>
                                        </div>
                                        <div>
                                            <span class="status-badge status-${item.status}">${item.status}</span>
                                        </div>
                                    </div>
                                </div>
                            `).join('')}
                        </div>
                    `;
                    container.innerHTML = html;
                } else {
                    container.innerHTML = `
                        <div class="empty-state">
                            <div class="empty-state-icon">🕐</div>
                            <h3>No Recent Activity</h3>
                            <p>Activity will appear here as you use the tool</p>
                        </div>
                    `;
                }
            }
        }

        async function loadLogs() {
            const response = await fetch('/api/logs?per_page=50');
            const data = await response.json();

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

            if (data.success && data.logs.length > 0) {
                const table = `
                    <table class="logs-table">
                        <thead>
                            <tr>
                                <th>Time</th>
                                <th>File</th>
                                <th>Action</th>
                                <th>Status</th>
                                <th>Tokens</th>
                                <th>Cost</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${data.logs.map(log => `
                                <tr>
                                    <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>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                `;
                container.innerHTML = table;
            } else {
                container.innerHTML = `
                    <div class="empty-state">
                        <div class="empty-state-icon">📋</div>
                        <h3>No Audit Logs</h3>
                        <p>Logs will appear here as operations are performed</p>
                    </div>
                `;
            }
        }

        function switchTab(tabName) {
            // Update tabs
            document.querySelectorAll('.tab').forEach(tab => tab.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));

            // Show selected tab
            event.target.classList.add('active');
            document.getElementById(tabName).classList.add('active');

            // Reload data for that tab if needed
            if (tabName === 'sessions') loadSessions();
            if (tabName === 'activity') loadRecentActivity();
            if (tabName === 'logs') loadLogs();
        }

        // Auto-refresh every 30 seconds
        setInterval(() => {
            loadData();
        }, 30000);
    </script>
</body>
</html>
