# Copyright (c) 2026 동일비전(Dongil Vision Korea). All Rights Reserved.
"""
╔══════════════════════════════════════════════════════════════════════════════╗
║  ALASKA v2.1 - Web Debugger UI (Modern Redesign)                             ║
║  High-Visibility Dark Interface for Real-time Monitoring                     ║
╚══════════════════════════════════════════════════════════════════════════════╝
"""

def render_debug_page(app_info):
    name = app_info.get("name", "ALASKA")
    version = app_info.get("version", "2.1")
    
    html = '''<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>''' + name + ''' Inspector - ALASKA v''' + version + '''</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        mermaid.initialize({ startOnLoad: false, theme: 'dark' });
    </script>
    <style>
        :root {
            --bg-color: #0f111a;
            --card-bg: #1a1d2b;
            --accent-color: #00d2ff;
            --text-main: #e0e6ed;
            --text-dim: #94a3b8;
            --success: #10b981;
            --danger: #ef4444;
            --warning: #f59e0b;
            --rmi-color: #bf94ff;
        }
        
        body {
            background-color: var(--bg-color);
            color: var(--text-main);
            font-family: 'Inter', system-ui, -apple-system, sans-serif;
            margin: 0;
            overflow-x: hidden;
        }

        .navbar {
            background-color: rgba(26, 29, 43, 0.8) !important;
            backdrop-filter: blur(10px);
            border-bottom: 1px solid rgba(255,255,255,0.05);
            padding: 1rem 2rem;
        }

        .nav-brand-text {
            font-weight: 800;
            letter-spacing: -0.5px;
            background: linear-gradient(90deg, #00d2ff 0%, #3a7bd5 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .container-fluid { padding: 2rem; }

        .glass-card {
            background: var(--card-bg);
            border: 1px solid rgba(255,255,255,0.05);
            border-radius: 16px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            transition: transform 0.2s ease;
            margin-bottom: 1.5rem;
        }

        .card-header-custom {
            padding: 1.25rem;
            border-bottom: 1px solid rgba(255,255,255,0.05);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .card-title-text {
            font-size: 1.1rem;
            font-weight: 600;
            color: var(--accent-color);
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .table-dark-custom {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0 8px;
        }

        .table-dark-custom th {
            color: var(--text-dim);
            font-weight: 500;
            text-transform: uppercase;
            font-size: 0.75rem;
            padding: 0 1rem;
        }

        .table-dark-custom td {
            background: rgba(255,255,255,0.02);
            padding: 1rem;
            vertical-align: middle;
        }

        .table-dark-custom tr td:first-child { border-top-left-radius: 12px; border-bottom-left-radius: 12px; }
        .table-dark-custom tr td:last-child { border-top-right-radius: 12px; border-bottom-right-radius: 12px; }

        .sig-badge {
            padding: 4px 10px;
            border-radius: 6px;
            font-size: 0.85rem;
            font-weight: 600;
            background: rgba(0, 210, 255, 0.1);
            color: var(--accent-color);
        }

        #trace-container {
            max-height: 600px;
            overflow-y: auto;
            scrollbar-width: thin;
            scrollbar-color: var(--accent-color) transparent;
        }

        .trace-item {
            padding: 0.75rem 1rem;
            border-left: 4px solid var(--accent-color);
            background: rgba(255,255,255,0.03);
            margin-bottom: 6px;
            border-radius: 4px;
            font-family: 'JetBrains Mono', monospace;
            font-size: 0.85rem;
            animation: fadeIn 0.3s ease;
        }

        .trace-item.rmi-call {
            border-left-color: var(--rmi-color);
            background: rgba(191, 148, 255, 0.05);
            box-shadow: inset 5px 0 15px rgba(191, 148, 255, 0.1);
        }

        .trace-item.qos-violation {
            border-left-color: var(--danger);
            background: rgba(239, 68, 68, 0.05);
            box-shadow: inset 5px 0 15px rgba(239, 68, 68, 0.1);
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(5px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .btn-glow {
            border-radius: 10px;
            padding: 0.5rem 1.25rem;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .btn-glow-primary {
            background: var(--accent-color);
            border: none;
            color: #000;
        }

        .status-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 6px;
            box-shadow: 0 0 10px currentColor;
        }
    </style>
</head>
<body>
    <nav class="navbar sticky-top">
        <span class="navbar-brand mb-0 h1">
            <i class="bi bi-cpu-fill text-info me-2"></i>
            <span class="nav-brand-text">ALASKA INSPECTOR</span>
            <span class="ms-2 badge bg-secondary" style="font-size: 0.6rem;">v''' + version + '''</span>
        </span>
        <div class="d-flex gap-3">
            <div id="connection-status">
                <span class="status-dot text-success" style="background-color: var(--success);"></span>
                <small class="text-dim">CONNECTED</small>
            </div>
            <a href="/" class="btn btn-outline-light btn-sm"><i class="bi bi-house-door"></i> Dashboard</a>
        </div>
    </nav>

    <div class="container-fluid">
        <ul class="nav nav-tabs mb-4 border-0" id="debugTabs" role="tablist">
            <li class="nav-item">
                <button class="nav-link active text-white border-0" style="background:transparent;" id="trace-tab" data-bs-toggle="tab" data-bs-target="#tab-trace" type="button">📡 REAL-TIME TRACE</button>
            </li>
            <li class="nav-item">
                <button class="nav-link text-white border-0" style="background:transparent;" id="sequence-tab" data-bs-toggle="tab" data-bs-target="#tab-sequence" type="button" onclick="renderSequence()">⏱️ SEQUENCE CHART</button>
            </li>
            <li class="nav-item">
                <button class="nav-link text-white border-0" style="background:transparent;" id="arch-tab" data-bs-toggle="tab" data-bs-target="#tab-arch" type="button" onclick="loadArch()">🗺️ SYSTEM ARCHITECTURE</button>
            </li>
            <li class="nav-item">
                <button class="nav-link text-white border-0" style="background:transparent;" id="static-seq-tab" data-bs-toggle="tab" data-bs-target="#tab-static-seq" type="button" onclick="loadStaticSeq()">📐 STATIC SEQUENCE</button>
            </li>
        </ul>

        <div class="tab-content" id="debugTabsContent">
            <div class="tab-pane fade show active" id="tab-trace" role="tabpanel">
                <div class="row">
                    <div class="col-lg-7">
                        <div class="glass-card h-100">
                            <div class="card-header-custom">
                                <div class="card-title-text"><i class="bi bi-activity"></i> Signal Registry Statistics</div>
                                <button onclick="clearStats()" class="btn btn-outline-danger btn-sm"><i class="bi bi-trash"></i> Reset</button>
                            </div>
                            <div class="card-body p-4">
                                <table class="table-dark-custom" id="sig-stats-table">
                                    <thead><tr><th>Signal Name</th><th class="text-center">Cumulative Count</th><th class="text-end">Last Activity</th></tr></thead>
                                    <tbody id="sig-stats-body"></tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-5">
                        <div class="glass-card">
                            <div class="card-header-custom">
                                <div class="card-title-text"><i class="bi bi-lightning-charge"></i> Live Signal Trace</div>
                                <div class="d-flex gap-2 align-items-center">
                                    <div class="form-check form-switch me-2">
                                        <input class="form-check-input" type="checkbox" id="check-urgent-only" onchange="updateTrace(true)">
                                        <label class="form-check-label text-dim" style="font-size: 0.75rem;" for="check-urgent-only">URGENT ONLY</label>
                                    </div>
                                    <button id="btn-toggle-trace" onclick="toggleTrace()" class="btn btn-glow btn-glow-primary btn-sm">START</button>
                                    <button onclick="clearTrace()" class="btn btn-outline-light btn-sm">CLEAR</button>
                                </div>
                            </div>
                            <div class="card-body p-3"><div id="trace-container"><div class="text-center text-muted py-5" id="trace-empty-hint">Click START to monitor traffic</div></div></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="tab-pane fade" id="tab-arch" role="tabpanel">
                <div class="glass-card p-4">
                    <div class="card-header-custom border-0">
                        <div class="card-title-text"><i class="bi bi-map"></i> Auto-Generated Topology</div>
                        <button onclick="loadArch()" class="btn btn-outline-info btn-sm">Refresh Map</button>
                    </div>
                    <div id="arch-container" class="mermaid text-center py-5" style="background: rgba(255,255,255,0.02); border-radius: 12px;"></div>
                </div>
            </div>

            <div class="tab-pane fade" id="tab-static-seq" role="tabpanel">
                <div class="glass-card p-4">
                    <div class="card-header-custom border-0">
                        <div class="card-title-text"><i class="bi bi-diagram-3"></i> Static Signal Flow (Code Analysis)</div>
                        <button onclick="loadStaticSeq()" class="btn btn-outline-info btn-sm">Refresh</button>
                    </div>
                    <div id="static-seq-container" class="mermaid text-center py-5" style="background: rgba(255,255,255,0.02); border-radius: 12px; overflow-x: auto;"></div>
                </div>
            </div>

            <div class="tab-pane fade" id="tab-sequence" role="tabpanel">
                <div class="glass-card p-4">
                    <div class="card-header-custom border-0">
                        <div class="card-title-text"><i class="bi bi-clock-history"></i> Flow Interaction Chart</div>
                        <div class="d-flex gap-2">
                            <input type="text" id="seq-filter" class="form-control form-control-sm bg-dark text-white" placeholder="Filter..." onchange="renderSequence()">
                            <button onclick="renderSequence()" class="btn btn-outline-info btn-sm">Refresh</button>
                        </div>
                    </div>
                    <div id="seq-container" class="mermaid text-center py-5" style="background: rgba(255,255,255,0.02); border-radius: 12px; overflow-x: auto;"></div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let isTracing = false;
        let lastTraceTime = 0;

        async function renderSequence() {
            try {
                const res = await fetch('/api/debug/signal/trace?limit=50');
                const data = await res.json();
                const container = document.getElementById('seq-container');
                if (!data.events || data.events.length === 0) return;
                let mermaidText = "sequenceDiagram\\n";
                const participants = new Set();
                data.events.forEach(e => {
                    participants.add(e.source);
                    if (e.targets) e.targets.forEach(t => participants.add(t));
                });
                participants.forEach(p => mermaidText += `  participant ${p}\\n`);
                const filter = document.getElementById('seq-filter').value.toLowerCase();
                data.events.forEach(e => {
                    if (filter && !e.signal.toLowerCase().includes(filter)) return;
                    const isRmi = e.signal.startsWith('RMI::');
                    const sigName = isRmi ? e.signal.substring(5) : e.signal;
                    // RMI: 점선 화살표 (-->>)
                    if (isRmi && e.data_preview) {
                        const m = e.data_preview.match(/->\\s*(\\w+)/);
                        if (m && participants.has(m[1])) {
                            mermaidText += `  ${e.source} -->> ${m[1]}: ${sigName}\\n`;
                            return;
                        }
                    }
                    // Signal: on_ 구독자(targets)로 실선 화살표 (->>)
                    if (e.targets && e.targets.length > 0) {
                        e.targets.forEach(t => {
                            if (participants.has(t)) {
                                mermaidText += `  ${e.source} ->> ${t}: ${sigName}\\n`;
                            }
                        });
                        return;
                    }
                    // 수신자 없음 → Note over
                    mermaidText += `  Note over ${e.source}: ${sigName}\\n`;
                });
                container.removeAttribute('data-processed');
                container.innerHTML = mermaidText;
                await mermaid.run({ nodes: [container] });
            } catch(e) { console.error(e); }
        }

        async function loadStaticSeq() {
            try {
                const res = await fetch('/api/debug/sequence');
                const data = await res.json();
                const container = document.getElementById('static-seq-container');
                if (data.map) {
                    container.removeAttribute('data-processed');
                    container.innerHTML = data.map;
                    await mermaid.run({ nodes: [container] });
                }
            } catch(e) { console.error(e); }
        }

        async function loadArch() {
            try {
                const res = await fetch('/api/debug/architecture');
                const data = await res.json();
                const container = document.getElementById('arch-container');
                if (data.map) {
                    container.removeAttribute('data-processed');
                    container.innerHTML = data.map;
                    await mermaid.run({ nodes: [container] });
                }
            } catch(e) { console.error(e); }
        }

        async function updateStats() {
            try {
                const res = await fetch('/api/subscriptions');
                const data = await res.json();
                const body = document.getElementById('sig-stats-body');
                if (!data.stats || !data.stats.signals) return;
                let html = '';
                const sorted = Object.entries(data.stats.signals).sort((a,b) => b[1].last_time - a[1].last_time);
                for (const [name, s] of sorted) {
                    const last = new Date(s.last_time * 1000).toLocaleTimeString('ko-KR', {hour12: false, fractionalSecondDigits: 2});
                    html += `<tr><td><span class="sig-badge"># ${name}</span></td><td class="text-center font-monospace">${s.count.toLocaleString()}</td><td class="text-end text-dim">${last}</td></tr>`;
                }
                body.innerHTML = html || '<tr><td colspan="3">No signals</td></tr>';
            } catch(e) { console.error(e); }
        }

        async function toggleTrace() {
            const btn = document.getElementById('btn-toggle-trace');
            const action = isTracing ? 'stop' : 'start';
            try {
                const res = await fetch('/api/debug/signal/trace', { method: 'POST', body: JSON.stringify({action: action}) });
                const data = await res.json();
                isTracing = data.recording;
                btn.innerText = isTracing ? 'STOP' : 'START';
                btn.className = isTracing ? 'btn btn-glow btn-danger btn-sm' : 'btn btn-glow btn-glow-primary btn-sm';
                if (isTracing) document.getElementById('trace-empty-hint').style.display = 'none';
            } catch(e) { console.error(e); }
        }

        async function updateTrace(force = false) {
            if (!isTracing && !force) return;
            try {
                const res = await fetch('/api/debug/signal/trace?limit=50');
                const data = await res.json();
                const container = document.getElementById('trace-container');
                const urgentOnly = document.getElementById('check-urgent-only').checked;
                let events = data.events;
                if (urgentOnly) events = events.filter(e => e.signal.startsWith('VIOLATION::') || e.signal.startsWith('RMI::') || e.signal.includes('urgent'));
                const newEvents = events.filter(e => e.ts > lastTraceTime);
                if (newEvents.length > 0) {
                    newEvents.forEach(e => {
                        const time = new Date(e.ts * 1000).toLocaleTimeString('ko-KR', {hour12: false, fractionalSecondDigits: 2});
                        const div = document.createElement('div');
                        const isRmi = e.signal.startsWith('RMI::');
                        const isViolation = e.signal.startsWith('VIOLATION::');
                        let displayName = e.signal, itemClass = 'trace-item', badgeStyle = 'background:rgba(0,210,255,0.1);color:#00d2ff;', icon = '<i class="bi bi-broadcast"></i>', badgeText = 'SIGNAL';
                        if (isRmi) { displayName = e.signal.substring(5); itemClass = 'trace-item rmi-call'; badgeStyle = 'background:rgba(191,148,255,0.3);color:#e9d5ff;border:1px solid rgba(191,148,255,0.5);'; icon = '<i class="bi bi-cpu-fill" style="color:#bf94ff"></i>'; badgeText = 'IPC CALL'; }
                        else if (isViolation) { displayName = e.signal.substring(11); itemClass = 'trace-item qos-violation'; badgeStyle = 'background:rgba(239,68,68,0.2);color:#fca5a5;border:1px solid #ef4444;'; icon = '<i class="bi bi-exclamation-triangle-fill" style="color:#ef4444"></i>'; badgeText = 'QoS VIOLATION'; }
                        div.className = itemClass;
                        div.innerHTML = `<div class="d-flex justify-content-between"><span><span class="text-info">[${time}]</span> ${icon} <b>${displayName}</b></span><span class="badge" style="${badgeStyle}">${badgeText}</span></div><div class="ms-4"><span class="text-dim">from</span> <span class="text-warning">${e.source}</span><br><small class="${isViolation?'text-danger':'text-muted'}">> ${e.data_preview}</small></div>`;
                        container.insertBefore(div, container.firstChild);
                        lastTraceTime = Math.max(lastTraceTime, e.ts);
                    });
                    while (container.children.length > 100) container.removeChild(container.lastChild);
                }
            } catch(e) { console.error(e); }
        }

        async function clearStats() { if (confirm('초기화 하시겠습니까?')) { await fetch('/api/subscriptions/clear', {method:'POST'}); updateStats(); } }
        async function clearTrace() { await fetch('/api/debug/signal/trace', {method:'POST', body:JSON.stringify({action:'clear'})}); document.getElementById('trace-container').innerHTML = ''; lastTraceTime = 0; }

        setInterval(updateStats, 1000);
        setInterval(updateTrace, 500);
        updateStats();
    </script>
</body></html>'''
    return html
