// Hermes Browser Agent — native messaging host bridge
const NATIVE_HOST = 'hermes.node.agent';
const WS_RETRY = 3000;

let ws = null;
let reconnectTimer = null;

function connectWebSocket() {
    const url = `ws://localhost:8765/hermes/browser`;  // matches gateway plugin route
    ws = new WebSocket(url);
    ws.onopen = () => console.log('[HermesExt] WS connected to gateway');
    ws.onclose = (e) => {
        console.log('[HermesExt] WS closed:', e.code, e.reason);
        ws = null;
        scheduleReconnect();
    };
    ws.onerror = (e) => console.error('[HermesExt] WS error', e);
    ws.onmessage = (m) => {
        try { handleNativeMessage(JSON.parse(m.data)); } catch(e) {}
    };
}

function scheduleReconnect() {
    if (reconnectTimer) clearTimeout(reconnectTimer);
    reconnectTimer = setTimeout(connectWebSocket, WS_RETRY);
}

// Route incoming messages from gateway to native host (Hermes Node Agent)
function handleNativeMessage(msg) {
    const {cmd, target, args, id} = msg;
    if (!cmd) return;

    // Forward to native host via native messaging
    sendToNative({cmd, target, args, id});
}

function sendToNative(data) {
    if (!window.nativePort) return;
    window.nativePort.postMessage(data);
}

// Lifecycle
chrome.runtime.onStartup.addListener(connectWebSocket);
chrome.runtime.onInstalled.addListener(connectWebSocket);
chrome.runtime.onConnectNative.addListener(port => {
    window.nativePort = port;
    port.onMessage.addListener(msg => sendToGateway(msg));
    port.onDisconnect.addListener(() => { window.nativePort = null; });
});

// Auto-reconnect
setInterval(connectWebSocket, 30000);
