import test from "node:test";
import assert from "node:assert/strict";
// @ts-ignore plain JS helper
import { PROVIDERS, PrefixCacheModel, anthropicPayload, bedrockPayload, explicitBlocks, atomsOf, googlePayload, openaiCompletionsPayload } from "./support/provider-cache-models.mjs";

// The models have to follow each provider's documented rules, or the walks that lean on them prove nothing.
const big = (label: string, chars = 5000) => `${label} ${"x".repeat(chars)}`;
const clock = () => { let t = 1_000_000; return { now: () => t, advance: (ms: number) => { t += ms; } }; };
const openai = (time: { now: () => number }) => new PrefixCacheModel({ name: "openai", minTokens: 1024, increment: 128, ttlMs: 10 * 60_000, keyed: true, now: time.now });

test("an automatic prefix cache reads in whole steps once the prompt reaches the minimum", () => {
	const model = openai(clock());
	const first = model.process({ key: "k", atoms: [big("sys", 6000)] });
	assert.equal(first.record.read, 0);
	// 6000 chars is 1501 tokens; the same prompt plus a little more reads 1024 plus whole 128-token steps.
	const second = model.process({ key: "k", atoms: [big("sys", 6000), "more text"] });
	assert.equal(second.record.read, 1024 + 128 * Math.floor((1501 - 1024) / 128));
});

test("a prompt under the minimum reads nothing", () => {
	const model = openai(clock());
	model.process({ key: "k", atoms: ["short prompt"] });
	assert.equal(model.process({ key: "k", atoms: ["short prompt", "next"] }).record.read, 0);
});

test("a prefix cache is shared only between requests with the same key", () => {
	const model = openai(clock());
	model.process({ key: "a", atoms: [big("sys")] });
	assert.equal(model.process({ key: "b", atoms: [big("sys"), "next"] }).record.read, 0);
	assert.ok(model.process({ key: "a", atoms: [big("sys"), "next"] }).record.read > 0);
});

test("a prefix cache entry expires after its lifetime, and a hit renews it", () => {
	const time = clock();
	const model = openai(time);
	const atoms = [big("sys")];
	model.process({ key: "k", atoms });
	time.advance(9 * 60_000);
	assert.ok(model.process({ key: "k", atoms }).record.read > 0);
	time.advance(9 * 60_000);
	assert.ok(model.process({ key: "k", atoms }).record.read > 0, "the hit nine minutes ago renewed it");
	time.advance(11 * 60_000);
	assert.equal(model.process({ key: "k", atoms }).record.read, 0);
});

test("a changed early part misses everything after it", () => {
	const model = openai(clock());
	model.process({ key: "k", atoms: [big("one"), big("two")] });
	assert.equal(model.process({ key: "k", atoms: [big("ONE"), big("two")] }).record.read, 0);
});

test("DeepSeek reads in 64-token units from the first one", () => {
	const model = PROVIDERS.deepseek.make({});
	model.process({ key: "", atoms: [big("a", 400)] });
	const read = model.process({ key: "", atoms: [big("a", 400), "tail"] }).record.read;
	assert.ok(read > 0 && read % 64 === 0, `read ${read}`);
});

const messages = [
	{ role: "user", content: "hello" },
	{ role: "assistant", content: [{ type: "toolCall", id: "c1", name: "read", arguments: { path: "x" } }] },
	{ role: "toolResult", toolCallId: "c1", content: "result" },
	{ role: "user", content: [{ type: "text", text: "next" }, { type: "image", data: "AAAA", mimeType: "image/png" }] },
];
const input = { system: "system prompt", tools: [{ name: "read", description: "Read", parameters: { type: "object" } }], messages };

test("payload builders keep tool calls and their results together, and mark the last user block", () => {
	const anthropic = anthropicPayload(input);
	assert.equal(anthropic.messages.length, 3, "the result and the next user message share one message");
	assert.ok(anthropic.messages.at(-1).content.at(-1).cache_control);
	const bedrock = bedrockPayload(input);
	assert.ok(bedrock.messages.at(-1).content.at(-1).cachePoint);
	assert.ok(bedrock.system.at(-1).cachePoint);
	const blocks = explicitBlocks("bedrock", bedrock);
	assert.equal(blocks.filter((block: any) => block.control).length, 2, "a cache point marks the block before it");
	assert.ok(blocks.every((block: any) => !block.text.includes("cachePoint")));
});

test("the same conversation gives the same prompt prefix in every provider's shape", () => {
	const longer = { ...input, messages: [...messages, { role: "assistant", content: "ok" }, { role: "user", content: "more" }] };
	for (const [api, build] of [["google-generative-ai", googlePayload], ["openai-completions", (i: any) => openaiCompletionsPayload(i)]] as const) {
		const a = atomsOf(api, build(input));
		const b = atomsOf(api, build(longer));
		assert.deepEqual(b.slice(0, a.length - 1), a.slice(0, a.length - 1), api);
	}
});
