import test from "node:test";
import assert from "node:assert/strict";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { fileURLToPath } from "node:url";

const support = (name: string) => fileURLToPath(new URL(`../support/${name}`, import.meta.url));

async function run(env: Record<string, string>, worker = support("prefix-lifecycle-sdk-worker.mjs"), args: string[] = []) {
	const { stdout } = await promisify(execFile)(process.execPath, ["--experimental-strip-types", worker, ...args], { timeout: 110000, env: { ...process.env, ...env } });
	return JSON.parse(stdout.trim().split("\n").at(-1)!);
}

test("real SDK, OpenAI-style: a goal's whole life keeps every request a prefix of the next", { timeout: 120000 }, async () => {
	const result = await run({ API: "openai" });
	assert.equal(result.passed, true);
	assert.equal(result.breaks, 0);
	assert.ok(result.requests >= 10);
});

test("real SDK, Anthropic with thinking blocks: cache breakpoints stay on reusable blocks", { timeout: 120000 }, async () => {
	const result = await run({ API: "anthropic", THINK: "1" });
	assert.equal(result.passed, true);
	assert.ok(result.worstMissedBlocks <= 8, `a request missed ${result.worstMissedBlocks} blocks`);
});

test("real SDK: another extension editing the newest message each request does not move the goal blocks", { timeout: 120000 }, async () => {
	const result = await run({ API: "openai", DECORATE: "1" });
	assert.equal(result.passed, true);
	assert.ok(result.moves <= 2, `the goal blocks moved ${result.moves} times`);
});

// Random walks: aborts, provider errors, steering, model switches, compaction, tree moves and restarts.
// Seed 9 also runs another extension that edits the newest message. Failures name the seed to replay with
// `node --experimental-strip-types tests/support/prefix-fuzz-sdk-worker.mjs <seed> 25` (add API=anthropic for the other mode).
// Each walk also runs against a mock of Anthropic's cache (tests/support/mock-anthropic-cache.mjs), which applies the
// real rules (breakpoints, 20-block lookback, minimum size, TTL); the worker checks that each request reads what the one before cached.
// The walks run side by side so the file stays inside the CI time limit for one check.
test("real SDK, random walks: every request starts with the one before, and the Anthropic cache model reads what was cached", { timeout: 150000 }, async () => {
	const walks = [4, 9].flatMap(seed => [{ seed, api: "openai" }, { seed, api: "anthropic" }]);
	const results = await Promise.all(walks.map(({ seed, api }) => run({ API: api }, support("prefix-fuzz-sdk-worker.mjs"), [String(seed), "25"])));
	for (const [i, result] of results.entries()) {
		assert.equal(result.passed, true, `seed ${walks[i]!.seed} on ${walks[i]!.api}`);
		assert.equal(result.api, walks[i]!.api);
		assert.ok(result.checked >= 10);
	}
});

test("real SDK, two sessions in one process keep their own prefixes", { timeout: 120000 }, async () => {
	const result = await run({}, support("prefix-two-sessions-sdk-worker.mjs"), ["3"]);
	assert.equal(result.passed, true);
	assert.ok(result.checked >= 8);
});
