import assert from "node:assert/strict";
import test from "node:test";
import { formatFailure, startCraftos, startFakeOpencode, startServer } from "./harness.js";

test("probe_server reports opencodeOk=true when opencode is healthy", async () => {
  const opencode = await startFakeOpencode({ status: 200 });
  const server = await startServer({ opencodeUrl: opencode.url });
  const craftos = startCraftos("gateway-client.lua", {
    computerId: 7,
    computerLabel: "health-ok",
    shellArgs: [server.baseUrl, "-", "health"],
  });
  try {
    const result = await craftos.done;
    assert.match(
      result.output,
      /__CLOUD_HEALTH__ serverOk=true opencodeOk=true/,
      formatFailure("expected serverOk=true opencodeOk=true", result.output),
    );
  } finally {
    craftos.abort();
    await craftos.done.catch(() => undefined);
    await server.close();
    await opencode.close();
  }
});

test("probe_server reports opencodeOk=false when opencode is unhealthy", async () => {
  const opencode = await startFakeOpencode({ status: 500 });
  const server = await startServer({ opencodeUrl: opencode.url });
  const craftos = startCraftos("gateway-client.lua", {
    computerId: 7,
    computerLabel: "health-bad",
    shellArgs: [server.baseUrl, "-", "health"],
  });
  try {
    const result = await craftos.done;
    assert.match(
      result.output,
      /__CLOUD_HEALTH__ serverOk=true opencodeOk=false/,
      formatFailure("expected serverOk=true opencodeOk=false", result.output),
    );
  } finally {
    craftos.abort();
    await craftos.done.catch(() => undefined);
    await server.close();
    await opencode.close();
  }
});
