/**
 * federation.js — Federation peer list + relay status + architects ward monitor.
 *
 * Fetches:
 *   GET /api/federation          → network status (peers, relay)
 *   GET /api/architects/wards    → dispatch status + worklist + active locks
 *   GET /api/architects/escalations → sentinel escalations
 *
 * Cut 25 (Phase H): Architects sentinel hardening + federation UI.
 */

import { api } from '../api.js';
import { S }   from '../state.js';

const $ = id => document.getElementById(id);
const esc = s => s == null ? '' : String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');

function fmtTs(ts) {
    if (!ts) return '—';
    return new Date(ts).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
}

function severityChip(sev) {
    const map = { critical: 'chip-bad', high: 'chip-bad', medium: 'chip-warn', low: 'chip-muted', info: 'chip-muted' };
    return `<span class="chip ${map[sev] || 'chip-muted'}">${esc(sev ?? 'info')}</span>`;
}

/* ── Load ─────────────────────────────────────────────────────────────────── */

export async function load() {
    const container = $('federation-container');
    if (!container) return;
    container.innerHTML = `<div class="empty"><div class="empty-title">Loading federation…</div></div>`;

    const [fed, wards, escs] = await Promise.all([
        api('/api/federation', 10_000),
        api('/api/architects/wards', 10_000),
        api('/api/architects/escalations', 10_000),
    ]);

    render(fed ?? {}, wards ?? {}, escs ?? {});
}

export function render(fed, wards, escs) {
    const container = $('federation-container');
    if (!container) return;

    const peers     = Array.isArray(fed.peers) ? fed.peers : (Array.isArray(fed.knownPeers) ? fed.knownPeers : []);
    const relay     = fed.relay ?? null;
    const relayMode = fed.relayMode ?? fed.relay?.mode ?? 'degraded';

    const dispatch    = wards.dispatch   ?? null;
    const worklist    = Array.isArray(wards.worklist)    ? wards.worklist    : [];
    const activeLocks = Array.isArray(wards.activeLocks) ? wards.activeLocks : [];
    const escalations = Array.isArray(escs.escalations)  ? escs.escalations  : [];

    container.innerHTML = `
        <div class="trust-grid">

            <!-- Relay status card -->
            <div class="card trust-card">
                <div class="trust-card-hd">
                    <span class="trust-card-title">Relay status</span>
                    <span class="chip ${relayMode === 'active' ? 'chip-ok' : relayMode === 'degraded' ? 'chip-warn' : 'chip-muted'}">${esc(relayMode)}</span>
                </div>
                ${relay ? `
                    <div class="trust-posture-body">
                        ${_kv('Relay host',    relay.host ?? (relay.configured ? 'configured' : 'local-only'))}
                        ${_kv('Relay port',    relay.port ?? '—')}
                        ${_kv('Transport',     relay.transport ?? 'local')}
                        ${_kv('Connected',     relay.connected ? 'yes' : 'no')}
                        ${_kv('Latency',       relay.latencyMs != null ? relay.latencyMs + ' ms' : '—')}
                    </div>
                ` : `<div class="empty-sub">Local-only mode. Add a relay when you want cross-machine federation.</div>`}
            </div>

            <!-- Peer list card -->
            <div class="card trust-card">
                <div class="trust-card-hd">
                    <span class="trust-card-title">Federation peers</span>
                    <span class="trust-card-count">${peers.length}</span>
                </div>
                ${peers.length === 0
                    ? `<div class="empty-sub">No federation peers detected.</div>`
                    : `<div class="trust-event-list">
                        ${peers.slice(0, 15).map(p => _peerRow(p)).join('')}
                       </div>`
                }
            </div>

            <!-- Dispatch governor card -->
            <div class="card trust-card">
                <div class="trust-card-hd">
                    <span class="trust-card-title">Dispatch governor</span>
                    ${dispatch?.throttled ? `<span class="chip chip-warn">throttled</span>` : `<span class="chip chip-ok">ok</span>`}
                </div>
                ${dispatch ? `
                    <div class="trust-posture-body">
                        ${_kv('Active',      dispatch.active ?? '—')}
                        ${_kv('Queue depth', dispatch.queueDepth ?? '—')}
                        ${_kv('Limit',       dispatch.limit ?? '—')}
                        ${_kv('Throttled',   dispatch.throttled ? 'yes' : 'no')}
                    </div>
                ` : `<div class="empty-sub">Architects dispatch is idle. Worklists appear when a mission attaches the Architects runtime.</div>`}
            </div>

            <!-- Active worklist card -->
            <div class="card trust-card">
                <div class="trust-card-hd">
                    <span class="trust-card-title">Active worklist</span>
                    <span class="trust-card-count">${worklist.length}</span>
                </div>
                ${worklist.length === 0
                    ? `<div class="empty-sub">No active work items.</div>`
                    : `<div class="trust-event-list">
                        ${worklist.slice(0, 10).map(w => _worklistRow(w)).join('')}
                       </div>`
                }
            </div>

            <!-- Active locks card -->
            ${activeLocks.length > 0 ? `
            <div class="card trust-card">
                <div class="trust-card-hd">
                    <span class="trust-card-title">Construction locks</span>
                    <span class="chip chip-warn">${activeLocks.length}</span>
                </div>
                <div class="trust-event-list">
                    ${activeLocks.slice(0, 10).map(l => _lockRow(l)).join('')}
                </div>
            </div>` : ''}

            <!-- Sentinel escalations card -->
            ${escalations.length > 0 ? `
            <div class="card trust-card trust-card-wide">
                <div class="trust-card-hd">
                    <span class="trust-card-title">Sentinel escalations</span>
                    <span class="chip chip-bad">${escalations.length}</span>
                </div>
                <div class="trust-event-list">
                    ${escalations.slice(0, 15).map(e => _escalationRow(e)).join('')}
                </div>
            </div>` : ''}

        </div>
    `;
}

/* ── Sub-renderers ────────────────────────────────────────────────────────── */

function _kv(label, value) {
    return `<div class="trust-row">
        <span class="trust-row-k">${esc(label)}</span>
        <span class="trust-row-v">${esc(String(value))}</span>
    </div>`;
}

function _peerRow(p) {
    const online = p.status === 'online' || p.health === 'online' || p.connected === true || p.active === true;
    return `
        <div class="trust-event-row">
            <div class="trust-event-main">
                <span class="chip ${online ? 'chip-ok' : 'chip-muted'}">${online ? 'online' : 'offline'}</span>
                <span class="trust-event-type">${esc(p.displayName ?? p.name ?? p.peerId ?? p.id ?? 'peer')}</span>
                ${p.host ? `<span style="font-family:var(--font-mono);font-size:var(--caption);color:var(--text-muted)">${esc(p.host)}</span>` : ''}
            </div>
            <div class="trust-event-meta">
                ${p.latencyMs != null ? `<span style="font-family:var(--font-mono);font-size:var(--caption);color:var(--text-muted)">${p.latencyMs}ms</span>` : ''}
                ${p.lastSeenAt || p.lastHeartbeat ? `<span style="color:var(--text-dim);font-size:var(--caption)">${fmtTs(p.lastSeenAt || p.lastHeartbeat)}</span>` : ''}
            </div>
        </div>`;
}

function _worklistRow(w) {
    const status = w.status ?? 'pending';
    const chipClass = status === 'running' ? 'chip-ok' : status === 'done' ? 'chip-muted' : status === 'failed' ? 'chip-bad' : 'chip-warn';
    return `
        <div class="trust-event-row">
            <div class="trust-event-main">
                <span class="chip ${chipClass}">${esc(status)}</span>
                <span class="trust-event-type">${esc(w.title ?? w.id ?? 'task')}</span>
                ${w.assignee ? `<span style="color:var(--text-muted);font-size:var(--text-sm)">${esc(String(w.assignee).slice(0, 30))}</span>` : ''}
            </div>
            <div class="trust-event-meta">
                <span style="color:var(--text-dim);font-size:var(--caption)">${fmtTs(w.updatedAt ?? w.createdAt)}</span>
            </div>
        </div>`;
}

function _lockRow(l) {
    return `
        <div class="trust-event-row">
            <div class="trust-event-main">
                <span class="chip chip-warn">locked</span>
                <span style="font-family:var(--font-mono);font-size:var(--text-sm)" class="trust-event-type">${esc(String(l.resource ?? l.lockId ?? '').slice(0, 40))}</span>
                ${l.holder ? `<span style="color:var(--text-muted);font-size:var(--text-sm)">${esc(String(l.holder).slice(0, 30))}</span>` : ''}
            </div>
            <div class="trust-event-meta">
                <span style="color:var(--text-dim);font-size:var(--caption)">${fmtTs(l.acquiredAt)}</span>
            </div>
        </div>`;
}

function _escalationRow(e) {
    return `
        <div class="trust-event-row">
            <div class="trust-event-main">
                ${severityChip(e.severity ?? 'high')}
                <span class="trust-event-type">${esc(e.wardId ?? e.type ?? 'escalation')}</span>
                ${e.message ? `<span style="color:var(--text-muted);font-size:var(--text-sm)">${esc(e.message.slice(0, 80))}</span>` : ''}
            </div>
            <div class="trust-event-meta">
                <span style="color:var(--text-dim);font-size:var(--caption)">${fmtTs(e.escalatedAt)}</span>
            </div>
        </div>`;
}
