/**
 * Bridge client (Forge-internal). Talks to lib/browser-bridge-standalone.ts
 * over loopback HTTP. Used by the chat backend's tool dispatcher to invoke
 * extension-side capabilities (chrome.scripting, chrome.tabs, etc.).
 *
 * The standalone routes each call to a connected extension via its
 * WebSocket. If no extension is paired/connected, this throws — the
 * dispatcher surfaces that as a tool_result with is_error.
 */

const BRIDGE_PORT = Number(process.env.BRIDGE_PORT) || 8407;

interface BridgeRpcOk { ok: true; value: unknown }
interface BridgeRpcErr { ok: false; error: string }

export async function bridgeRpc(method: string, params: unknown, timeoutMs?: number): Promise<unknown> {
  let res: Response;
  try {
    res = await fetch(`http://127.0.0.1:${BRIDGE_PORT}/api/rpc`, {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ method, params, ...(timeoutMs ? { timeout_ms: timeoutMs } : {}) }),
    });
  } catch (e) {
    throw new Error(`browser bridge unreachable on port ${BRIDGE_PORT}: ${(e as Error).message}`);
  }
  if (!res.ok) {
    throw new Error(`bridge http ${res.status}: ${await res.text().catch(() => '')}`);
  }
  const data = (await res.json()) as BridgeRpcOk | BridgeRpcErr;
  if (!data.ok) throw new Error(data.error || 'bridge rpc failed');
  return data.value;
}

/** Push an event to all connected extensions (e.g., chat token stream). */
export async function bridgePush(topic: string, payload: unknown): Promise<{ delivered_to: number }> {
  try {
    const r = await fetch(`http://127.0.0.1:${BRIDGE_PORT}/api/push`, {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ topic, payload }),
    });
    if (!r.ok) return { delivered_to: 0 };
    const j = await r.json();
    return { delivered_to: Number(j.delivered_to ?? 0) };
  } catch {
    return { delivered_to: 0 };
  }
}

export async function bridgeStatus(): Promise<{ connected_extensions: number; paired_extensions: number } | null> {
  try {
    const r = await fetch(`http://127.0.0.1:${BRIDGE_PORT}/api/status`);
    if (!r.ok) return null;
    return await r.json();
  } catch {
    return null;
  }
}
