import {
  ackWorkItem,
  completeWorkItem,
  getWorkItemInputs,
  heartbeatWorkItem,
  pollWorkItem
} from "./chunk-EDM5KER5.js";
import {
  runTurn
} from "./chunk-CRCDYAJC.js";

// src/workers/runner.ts
async function startWorker(opts) {
  const pollInterval = opts.pollIntervalMs ?? 5e3;
  const workerId = opts.workerId ?? `worker-${process.pid}`;
  let stopping = false;
  process.on("SIGINT", () => {
    stopping = true;
  });
  process.on("SIGTERM", () => {
    stopping = true;
  });
  console.log(`[worker] starting: env=${opts.environmentId} poll=${pollInterval}ms worker=${workerId}`);
  while (!stopping) {
    const item = pollWorkItem(opts.environmentId, workerId);
    if (!item) {
      await new Promise((r) => setTimeout(r, pollInterval));
      continue;
    }
    console.log(`[worker] claimed ${item.id} -> session ${item.data.id}`);
    const acked = ackWorkItem(item.id, workerId);
    if (!acked) {
      console.warn(`[worker] ack failed for ${item.id} \u2014 another worker claimed it`);
      continue;
    }
    const heartbeatTimer = setInterval(() => {
      const result = heartbeatWorkItem(item.id);
      if (result && !result.lease_extended) {
        console.warn(`[worker] heartbeat failed for ${item.id}: state=${result.state}`);
      }
    }, 3e4);
    try {
      const inputsRaw = getWorkItemInputs(item.id);
      const inputs = inputsRaw ? JSON.parse(inputsRaw) : [];
      if (inputs.length > 0) {
        await runTurn(item.data.id, inputs);
      } else {
        console.warn(`[worker] no inputs for ${item.id} \u2014 skipping`);
      }
      completeWorkItem(item.id, "completed");
      console.log(`[worker] completed ${item.id}`);
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      console.error(`[worker] failed ${item.id}: ${msg}`);
      completeWorkItem(item.id, "failed");
    } finally {
      clearInterval(heartbeatTimer);
    }
  }
  console.log("[worker] stopped");
}

export {
  startWorker
};
