import fs from "node:fs";
import path from "node:path";
import os from "node:os";

export function readRuntime() {
  try { return JSON.parse(fs.readFileSync(path.join(os.homedir(), ".alvin-bot", "state", "web-runtime.json"), "utf-8")); }
  catch { return null; }
}

export async function signalRunningBot(payload, opts = {}) {
  const runtime = opts.runtime !== undefined ? opts.runtime : readRuntime();
  const fetchImpl = opts.fetchImpl || fetch;
  const reqPath = opts.path || "/api/providers/set-primary";
  if (!runtime?.port || !runtime?.token) return { live: false };
  try {
    const res = await fetchImpl(`http://127.0.0.1:${runtime.port}${reqPath}`, {
      method: "POST",
      headers: { "Content-Type": "application/json", "Authorization": `Bearer ${runtime.token}` },
      body: JSON.stringify(payload),
    });
    return { live: !!res.ok, status: res.status };
  } catch { return { live: false }; }
}
