---
// src/pages/admin/db-console.astro
import Layout from '@/layouts/BaseLayout.astro'; // Assuming BaseLayout exists, or check existing layout
import { MECHANIC_OPS } from '@/lib/db/mechanic';

// Server-side Logic (runs on build or request in SSR)
let health;
try {
    health = await MECHANIC_OPS.getHealth();
} catch (e) {
    console.error('Failed to get health:', e);
    health = { 
        size: 'Error', 
        connections: [], 
        cache: { ratio: 0 } 
    };
}

const activeConnections = health.connections.find((c: any) => c.state === 'active')?.active || 0;
const idleConnections = health.connections.find((c: any) => c.state === 'idle')?.active || 0;
const token = import.meta.env.GOD_MODE_TOKEN || '';
---

<html lang="en" class="dark">
<head>
    <meta charset="UTF-8">
    <title>DB Command Center - Valhalla</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            darkMode: 'class',
            theme: {
                extend: {
                    colors: {
                        zinc: { 800: '#27272a', 900: '#18181b' }
                    }
                }
            }
        }
    </script>
</head>
<body class="bg-zinc-900 text-white min-h-screen">
    <div class="p-8 space-y-8 max-w-7xl mx-auto">
        
        <header class="flex justify-between items-center mb-8">
            <div>
                <h1 class="text-3xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-yellow-400 to-red-500">
                     Valhalla DB Command Center
                </h1>
                <p class="text-gray-400">Direct PostgreSQL Interface</p>
            </div>
            <a href="/" class="text-gray-400 hover:text-white">Back to Dashboard</a>
        </header>

        <!-- Stats Grid -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div class="bg-zinc-800 p-6 rounded-lg border-l-4 border-green-500 shadow-lg">
                <h3 class="text-gray-400 text-sm uppercase font-semibold">DB Size</h3>
                <p class="text-4xl font-bold mt-2">{health.size}</p>
            </div>
            <div class="bg-zinc-800 p-6 rounded-lg border-l-4 border-blue-500 shadow-lg">
                <h3 class="text-gray-400 text-sm uppercase font-semibold">Connections</h3>
                <div class="flex items-end gap-2 mt-2">
                    <p class="text-4xl font-bold">{activeConnections}</p>
                    <span class="text-xl text-gray-500">active</span>
                </div>
                <p class="text-sm text-gray-500 mt-1">{idleConnections} idle</p>
            </div>
            <div class="bg-zinc-800 p-6 rounded-lg border-l-4 border-purple-500 shadow-lg">
                <h3 class="text-gray-400 text-sm uppercase font-semibold">Cache Efficiency</h3>
                <p class="text-4xl font-bold mt-2">{Math.round(health.cache.ratio * 100)}%</p>
            </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            
            <!-- Emergency Controls -->
            <div class="bg-zinc-800/50 border border-zinc-700 p-6 rounded-xl">
                <h2 class="text-xl mb-6 text-red-400 flex items-center gap-2">
                    <span>🚨</span> Emergency Fixes
                </h2>
                <div class="space-y-4">
                    <button onclick="runOp('vacuum')" class="w-full group relative overflow-hidden bg-yellow-600 hover:bg-yellow-500 transition-all p-4 rounded-lg font-bold text-left flex justify-between items-center">
                        <div>
                            <div class="text-white">Run Vacuum</div>
                            <div class="text-xs text-yellow-200 opacity-70">Optimize dead rows</div>
                        </div>
                        <span class="text-2xl opacity-50 group-hover:opacity-100">🧹</span>
                    </button>
                    
                    <button onclick="runOp('reindex')" class="w-full group relative overflow-hidden bg-orange-600 hover:bg-orange-500 transition-all p-4 rounded-lg font-bold text-left flex justify-between items-center">
                        <div>
                            <div class="text-white">Reindex Database</div>
                            <div class="text-xs text-orange-200 opacity-70">Fix corrupted indexes</div>
                        </div>
                        <span class="text-2xl opacity-50 group-hover:opacity-100">📑</span>
                    </button>

                    <button onclick="runOp('kill_locks')" class="w-full group relative overflow-hidden bg-red-700 hover:bg-red-600 transition-all p-4 rounded-lg font-bold text-left flex justify-between items-center">
                        <div>
                            <div class="text-white">Kill Stuck Queries</div>
                            <div class="text-xs text-red-200 opacity-70">Terminate > 5min processes</div>
                        </div>
                        <span class="text-2xl opacity-50 group-hover:opacity-100">💀</span>
                    </button>
                </div>
            </div>

            <!-- Throttles -->
            <div class="lg:col-span-2 bg-zinc-800/50 border border-zinc-700 p-6 rounded-xl">
                <h2 class="text-xl mb-6 text-blue-400 flex items-center gap-2">
                    <span>🎚️</span> Factory Throttles
                </h2>
                
                <form id="throttleForm" class="space-y-8">
                    <div class="space-y-2">
                        <div class="flex justify-between">
                            <label class="font-medium text-gray-300">Batch Size (Items per Chunk)</label>
                            <span class="text-blue-400 font-mono" id="batchOutput">100</span>
                        </div>
                        <input type="range" min="10" max="1000" value="100" step="10" 
                            class="w-full h-2 bg-zinc-700 rounded-lg appearance-none cursor-pointer accent-blue-500"
                            oninput="document.getElementById('batchOutput').textContent = this.value + ' rows'">
                        <p class="text-sm text-gray-500">Higher values use more memory but process faster.</p>
                    </div>

                    <div class="space-y-2">
                         <div class="flex justify-between">
                            <label class="font-medium text-gray-300">Concurrency (Parallel Workers)</label>
                            <span class="text-blue-400 font-mono" id="concurrencyOutput">5</span>
                        </div>
                        <input type="range" min="1" max="50" value="5" step="1" 
                            class="w-full h-2 bg-zinc-700 rounded-lg appearance-none cursor-pointer accent-blue-500"
                             oninput="document.getElementById('concurrencyOutput').textContent = this.value + ' threads'">
                        <p class="text-sm text-gray-500">Higher values allow more simultaneous DB connections.</p>
                    </div>

                    <div class="pt-4 border-t border-zinc-700">
                        <button type="button" class="bg-blue-600 hover:bg-blue-500 text-white px-8 py-3 rounded-lg font-bold transition-colors">
                            Update Runtime Engine
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Hidden Token for Client Script -->
    <div id="god-token" data-token={token} style="display:none;"></div>

    <script is:inline>
        async function runOp(operation) {
            const token = document.getElementById('god-token')?.dataset.token;
            if(!confirm(`⚠️ Are you sure you want to RUN ${operation.toUpperCase()}? This may affect database performance.`)) return;
            
            try {
                const res = await fetch('/api/god/db-ops', { 
                    method: 'POST', 
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify({ operation }) 
                });
                
                const text = await res.text();
                if (res.ok) {
                    alert('✅ Success: ' + text);
                    location.reload();
                } else {
                    alert('❌ Error: ' + text);
                }
            } catch (err) {
                alert('Connection Error: ' + err.message);
            }
        }
    </script>
</body>
</html>
