const baseUrl = process.env.HWLAB_CASERUN_NATIVE_URL || "http://127.0.0.1:4316";

export {};

function requireCondition(condition: unknown, message: string): asserts condition {
  if (!condition) throw new Error(message);
}

async function readJson(path: string, init?: RequestInit): Promise<{ response: Response; body: Record<string, unknown> }> {
  const response = await fetch(`${baseUrl}${path}`, init);
  const body = await response.json();
  requireCondition(body && typeof body === "object" && !Array.isArray(body), `invalid JSON object from ${path}`);
  return { response, body };
}

const started = await readJson("/v1/caserun/runs", {
  method: "POST",
  headers: { "content-type": "application/json" },
  body: JSON.stringify({ caseId: "native-completed" })
});
requireCondition(started.response.status === 202, `start status=${started.response.status}`);
requireCondition(typeof started.body.runId === "string", "start runId missing");

await readJson(`/v1/caserun/runs/${encodeURIComponent(started.body.runId)}`);
const completed = await readJson(`/v1/caserun/runs/${encodeURIComponent(started.body.runId)}`);
requireCondition(completed.body.status === "completed", `run status=${completed.body.status}`);

const aggregate = await readJson(`/v1/caserun/runs/${encodeURIComponent(started.body.runId)}/aggregate`);
requireCondition(aggregate.response.status === 200, `aggregate httpStatus=${aggregate.response.status}`);
requireCondition(aggregate.body.mode === "native-test", `aggregate mode=${aggregate.body.mode}`);
requireCondition(aggregate.body.status === "completed", `aggregate status=${aggregate.body.status}`);
requireCondition(aggregate.body.runId === started.body.runId, `aggregate runId=${aggregate.body.runId}`);
requireCondition(typeof aggregate.body.sha256 === "string" && /^[a-f0-9]{64}$/.test(aggregate.body.sha256), `aggregate sha256=${aggregate.body.sha256}`);
const references = completed.body.references;
requireCondition(references && typeof references === "object" && !Array.isArray(references), "run aggregate reference missing");
const aggregateReference = (references as Record<string, unknown>).aggregate;
requireCondition(aggregateReference && typeof aggregateReference === "object" && !Array.isArray(aggregateReference), "run aggregate reference invalid");
requireCondition(aggregate.body.sha256 === (aggregateReference as Record<string, unknown>).sha256, "aggregate SHA does not match run reference");

console.log(JSON.stringify({
  ok: true,
  mode: aggregate.body.mode,
  path: `/v1/caserun/runs/${started.body.runId}/aggregate`,
  status: aggregate.body.status,
  runId: aggregate.body.runId,
  sha256: aggregate.body.sha256
}));
