// Copyright (C) 2026 Stefy Lanza <stefy@nexlab.net>
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyleft: this program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 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);
