import test from "node:test";
import assert from "node:assert/strict";
// @ts-ignore plain JS helper
import { AnthropicCacheModel } from "./support/mock-anthropic-cache.mjs";

// The mock has to follow the real caching rules, or the tests that lean on it prove nothing.
const big = (label: string) => `${label} ${"x".repeat(5000)}`; // ~1250 tokens
const ctl = { type: "ephemeral" };
const user = (text: string, cache = false) => ({ role: "user", content: [{ type: "text", text, ...(cache ? { cache_control: ctl } : {}) }] });
const clock = () => { let t = 1_000_000; return { now: () => t, advance: (ms: number) => { t += ms; } }; };

test("a first request writes the prefix and a repeat reads it", () => {
	const model = new AnthropicCacheModel();
	const body = { system: [{ type: "text", text: big("sys"), cache_control: ctl }], messages: [user("hi", true)] };
	const first = model.process(body).usage;
	assert.equal(first.cache_read_input_tokens, 0);
	assert.ok(first.cache_creation_input_tokens > 1000);
	const second = model.process(body).usage;
	assert.equal(second.cache_read_input_tokens, first.cache_creation_input_tokens);
	assert.equal(second.cache_creation_input_tokens, 0);
});

test("a longer conversation reads the earlier prefix and writes only the new part", () => {
	const model = new AnthropicCacheModel();
	const system = [{ type: "text", text: big("sys") }];
	const a = model.process({ system, messages: [user(big("one"), true)] }).usage;
	const b = model.process({ system, messages: [user(big("one")), { role: "assistant", content: [{ type: "text", text: "ok" }] }, user(big("two"), true)] }).usage;
	assert.equal(b.cache_read_input_tokens, a.cache_creation_input_tokens);
	assert.ok(b.cache_creation_input_tokens > 1000);
});

test("changing an early block misses everything after it", () => {
	const model = new AnthropicCacheModel();
	model.process({ system: [{ type: "text", text: big("sys") }], messages: [user(big("one"), true)] });
	const changed = model.process({ system: [{ type: "text", text: big("sys!") }], messages: [user(big("one"), true)] }).usage;
	assert.equal(changed.cache_read_input_tokens, 0);
});

test("cache_control markers are not part of what is matched", () => {
	const model = new AnthropicCacheModel();
	const first = model.process({ messages: [user(big("one"), true)] }).usage;
	const again = model.process({ messages: [user(big("one"), true), user("next")] }).usage;
	assert.equal(again.cache_read_input_tokens, first.cache_creation_input_tokens);
});

test("prefixes under the minimum are not cached", () => {
	const model = new AnthropicCacheModel();
	const body = { messages: [user("short", true)] };
	assert.equal(model.process(body).usage.cache_creation_input_tokens, 0);
	assert.equal(model.process(body).usage.cache_read_input_tokens, 0);
});

test("more than four breakpoints is an error", () => {
	const model = new AnthropicCacheModel();
	const result = model.process({ messages: [1, 2, 3, 4, 5].map(n => user(`m${n}`, true)) });
	assert.match(result.error, /maximum of 4/);
});

test("the lookback finds an earlier entry only within 20 blocks of a breakpoint", () => {
	const filler = (n: number) => Array.from({ length: n }, (_, i) => ({ role: i % 2 ? "assistant" : "user", content: [{ type: "text", text: `filler ${i}` }] }));
	const start = [user(big("start"), true)];
	for (const [extra, expectHit] of [[10, true], [30, false]] as const) {
		const model = new AnthropicCacheModel();
		const first = model.process({ messages: start }).usage;
		const tail = [...start.map(m => ({ ...m, content: m.content.map(({ cache_control, ...rest }: any) => rest) })), ...filler(extra), user(big("end"), true)];
		const second = model.process({ messages: tail }).usage;
		assert.equal(second.cache_read_input_tokens > 0, expectHit, `${extra} blocks later`);
		if (expectHit) assert.equal(second.cache_read_input_tokens, first.cache_creation_input_tokens);
	}
});

test("entries expire after five minutes, and a hit renews them", () => {
	const time = clock();
	const model = new AnthropicCacheModel({ now: time.now });
	const body = { messages: [user(big("one"), true)] };
	model.process(body);
	time.advance(4 * 60_000);
	assert.ok(model.process(body).usage.cache_read_input_tokens > 0);
	time.advance(4 * 60_000); // 8 minutes after the first, 4 after the renewal
	assert.ok(model.process(body).usage.cache_read_input_tokens > 0);
	time.advance(6 * 60_000);
	assert.equal(model.process(body).usage.cache_read_input_tokens, 0);
});

test("a one hour entry outlives five minutes", () => {
	const time = clock();
	const model = new AnthropicCacheModel({ now: time.now });
	const body = { messages: [{ role: "user", content: [{ type: "text", text: big("one"), cache_control: { type: "ephemeral", ttl: "1h" } }] }] };
	model.process(body);
	time.advance(30 * 60_000);
	assert.ok(model.process(body).usage.cache_read_input_tokens > 0);
});
