/**
 * runtime-badge.js — Push-mode runtime availability badges.
 *
 * Fetches GET /api/invokers and renders one pill per invoker in the
 * sidebar footer showing amber (unavailable) or green (available) status.
 *
 * Mounts into #runtime-badges (created by index.html in the sidebar foot).
 * Refreshes on mount only; runtime availability rarely flips mid-session.
 */

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

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

export async function mount() {
    await refresh();
}

export async function refresh() {
    const container = $('runtime-badges');
    if (!container) return;

    const runtimes = await api('/api/invokers', 8_000);
    if (!Array.isArray(runtimes)) return;

    container.innerHTML = runtimes.map(r => _badge(r)).join('');
}

function _badge(r) {
    const ok      = r.available === true;
    const chipCls = ok ? 'chip-ok' : 'chip-warn';
    const dot     = ok ? '●' : '○';
    const title   = ok
        ? `${r.label} — available${r.version ? ' v' + esc(r.version) : ''}`
        : `${r.label} — not in PATH (push mode unavailable; pull mode works)`;
    return `<span class="runtime-badge chip ${chipCls}" title="${esc(title)}">`
         + `<span aria-hidden="true">${dot}</span>`
         + `<span>${esc(r.label)}</span>`
         + `</span>`;
}
