/**
 * Random walks over a conversation and its goal, checked against what each provider's cache
 * would report. A walk is a list of plain operations, so a failing one can be replayed and
 * shrunk to the few operations that matter.
 *
 * Per request:
 * - the real messages come out unchanged, and no goal block sits inside a tool batch;
 * - the newest policy block and task list are the current ones;
 * - unless the history was rewritten on purpose, the request starts with the stable part of the
 *   one before, in the shape the provider receives (merged messages, cache markers moved);
 * - the provider's cache model then reports what that implies: a read of at least the earlier
 *   prefix while its entry is alive, nothing once it has expired, and the numbers add up;
 * - saved goal blocks restore to exactly what was live, unless a save failed or the file was damaged.
 */
import assert from "node:assert/strict";
import { GOAL_ENDED_STATE, GOAL_ON_HOLD_STATE, LiveTailRetention, MAX_RETAINED_LIVE_TAILS, MAX_RETAINED_POINTERS, TASK_LIST_NONE } from "../../extensions/goal-live-retention.ts";
import { saveLiveTails, restoreLiveTails } from "../../extensions/goal-live-persist.ts";
import { cacheGoalHistory } from "../../extensions/goal-prompt-cache.ts";
// @ts-ignore plain JS helpers
import { PROVIDERS, anthropicPayload, bedrockPayload, openaiCompletionsPayload, openaiResponsesPayload, googlePayload, explicitBlocks, atomsOf } from "./provider-cache-models.mjs";
// @ts-ignore plain JS helpers
import { blocksOf as anthropicBlocks } from "./mock-anthropic-cache.mjs";

export type Op = { t: string; r: number; n: number };
export type ProviderName = string;
export const PROVIDER_NAMES: ProviderName[] = Object.keys(PROVIDERS);

export function random(seed: number): () => number {
	let a = seed >>> 0;
	return () => {
		a = (a + 0x6d2b79f5) >>> 0;
		let t = a;
		t = Math.imul(t ^ (t >>> 15), t | 1);
		t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
		return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
	};
}

const WEIGHTS: Array<[string, number]> = [
	["grow", 6], ["tool", 4], ["parallel", 2], ["huge", 1], ["unicode", 1], ["image", 1],
	["request", 5], ["goal", 2], ["pause", 2], ["resume", 2], ["tasks", 3], ["end", 1], ["objective", 1],
	["decorate", 1], ["compact", 1], ["branch", 1], ["edit", 1], ["bulk", 0.5], ["hold", 1], ["unhold", 1], ["restart", 1.5], ["clock", 3],
];
const FAULT_WEIGHTS: Array<[string, number]> = [["crash", 1.5], ["corrupt", 1]];

/** The operations of one walk. `faults` adds failed saves and damaged session files. */
export function generate(seed: number, steps: number, faults = seed % 4 === 0): Op[] {
	const rand = random(seed);
	const table = faults ? [...WEIGHTS, ...FAULT_WEIGHTS] : WEIGHTS;
	const total = table.reduce((sum, [, weight]) => sum + weight, 0);
	return Array.from({ length: steps }, () => {
		let pick = rand() * total;
		let t = table[0]![0];
		for (const [name, weight] of table) { if ((pick -= weight) < 0) { t = name; break; } }
		return { t, r: rand(), n: Math.floor(rand() * 1000) };
	});
}

const SYSTEM = `You are a coding agent. ${"Follow the repository rules and keep answers short. ".repeat(80)}`;
const TOOLS = ["read", "write", "bash"].map(name => ({ name, description: `Run ${name}. ${"Details. ".repeat(40)}`, parameters: { type: "object", properties: { path: { type: "string" } } } }));
const isLive = (message: any): boolean => message?.customType === "pi-goal-live-context";

interface Goal { id: string; version: number; tasks: number; status: "active" | "paused" | "ended" }
const policyFor = (goal: Goal): string => `[PI GOAL ${goal.status.toUpperCase()} goalId=${goal.id} v=${goal.version}]\nObjective ${goal.id} version ${goal.version}. ${"Keep going. ".repeat(20)}`;

function freshFor(goal: Goal | undefined, usage: number, holding: boolean): { state: string; counters?: string; ephemeral?: string; scope?: string; interim?: boolean; onlyIfSent?: boolean } {
	if (holding) return { state: GOAL_ON_HOLD_STATE, interim: true, onlyIfSent: true };
	if (!goal || goal.status === "ended") return { state: GOAL_ENDED_STATE, interim: true, onlyIfSent: true };
	const counters = goal.tasks > 0 && goal.status === "active" ? `[TASK LIST ${goal.id}] tasks version ${goal.tasks}\n- a\n- b` : undefined;
	return { state: policyFor(goal), ...(counters ? { counters } : {}), ephemeral: `usage ${usage}`, scope: `${goal.id}:${goal.version}` };
}

function sharedPrefix(a: string[], b: string[]): number {
	let i = 0;
	while (i < a.length && i < b.length && a[i] === b[i]) i++;
	return i;
}

const UNICODE = "日本語のテキスト 🚀🎉 مرحبا بالعالم é ​‍ 😀 \ud800 end";
const filler = (kb: number, seed: number): string => { let out = ""; for (let i = 0; out.length < kb * 1024; i++) out += `line ${seed}-${i} ${"abcdefghij".repeat(6)}\n`; return out; };
const base64 = (kb: number, seed: number): string => Buffer.from(filler(kb, seed)).toString("base64").slice(0, kb * 1024);

const MINUTE = 60_000;

export interface WalkOptions { provider: ProviderName; seed: number; log?: string[] }

/** Run the operations. Throws on the first broken rule. */
export function execute(ops: Op[], { provider, seed, log = [] }: WalkOptions): void {
	const spec = PROVIDERS[provider];
	let now = 1_800_000_000_000;
	const cache = spec.make({ now: () => now });
	const ttlOption = seed % 5 === 0 && spec.explicit ? "1h" : undefined;
	const ttlMs = ttlOption ? 60 * MINUTE : spec.ttlMs;
	const sessionKey = `walk-${seed}`;

	let clock = 1;
	const msg = (role: string, content: unknown, extra: Record<string, unknown> = {}): any => ({ role, content, timestamp: clock++, ...extra });
	let history: any[] = [msg("user", "start")];
	const entries: Array<{ type: "custom"; customType: string; data: unknown }> = [];
	const key = JSON.stringify(["session", "provider", "model"]);
	const model = "provider/model";
	let live = new LiveTailRetention();
	let goals = 0;
	let current: Goal | undefined;
	let usage = 0;
	let decorating = false;
	let holding = false;
	let rewritten = false;
	let edited = false;
	let calls = 0;
	let savedHistory: string | undefined;
	let crashAfter = -1;
	let failedSaves = 0;
	let savesSinceFailure = 0;
	let corrupted = false;
	let previous: { stableAtoms: string[]; atoms: string[]; lastBreakpointTokens?: number; lastBreakpointBlock?: number; at: number } | undefined;
	let previousBase: string[] = [];
	let previousDecorated = false;

	const view = (): any[] => history.map((m, i) => decorating && i === history.length - 1 && typeof m.content === "string" ? { ...m, content: `${m.content} [note ${usage}]` } : { ...m });

	const save = () => {
		let written = 0;
		try {
			saveLiveTails(live, key, model, view(), (type, data) => {
				if (crashAfter >= 0 && written >= crashAfter) { crashAfter = -1; throw new Error("disk full"); }
				written++;
				entries.push({ type: "custom", customType: type, data });
			});
			savedHistory = JSON.stringify(view());
			savesSinceFailure++;
		} catch {
			// Saving is best effort in the extension; the walk goes on.
			failedSaves++;
			savesSinceFailure = 0;
		}
	};

	const payloadFor = (messages: any[]): any => {
		const input = { system: SYSTEM, tools: TOOLS, messages, ttl: ttlOption };
		switch (provider) {
			case "anthropic": return anthropicPayload(input);
			case "bedrock": return bedrockPayload(input);
			case "openrouter-anthropic": return openaiCompletionsPayload({ ...input, anthropicStyle: true });
			case "openai": return openaiResponsesPayload({ ...input, cacheKey: sessionKey });
			case "google": return googlePayload(input);
			case "openai-completions": return openaiCompletionsPayload({ ...input, cacheKey: sessionKey });
			default: return openaiCompletionsPayload(input);
		}
	};
	/** The prompt as an ordered list of strings, without cache markers. */
	const atomsFor = (payload: any): string[] => {
		if (provider === "anthropic") return anthropicBlocks(payload).map((block: any) => block.text);
		if (spec.explicit) return explicitBlocks(provider, payload).map((block: any) => block.text);
		return atomsOf(spec.api, payload);
	};

	const request = (step: number, what: string) => {
		const tag = `${provider} seed ${seed} step ${step} (${what})`;
		// Requests end with a user message, as Pi's do.
		if (history.at(-1)?.role === "assistant") history.push(msg("user", `go on ${step}`));
		usage++;
		calls++;
		const base = view();
		const baseJson = base.map(m => JSON.stringify(m));
		// More than two earlier messages with new text counts as a rewrite.
		if (baseJson.slice(0, previousBase.length).filter((m, i) => m !== previousBase[i]).length > 2) rewritten = true;
		const before = live.restartInfo();
		const fresh = freshFor(current, usage, holding);
		const out = live.apply(key, base, fresh);
		const restartedNow = live.restartInfo().count > before.count;

		// Rules about the messages themselves.
		assert.deepEqual(out.messages.filter(m => !isLive(m)), base, `${tag}: real messages changed`);
		out.messages.forEach((m, i) => {
			if (m.role === "toolResult") assert.ok(!isLive(out.messages[i - 1]), `${tag}: a goal block sits before a tool result`);
		});
		const stable = out.messages.slice(0, out.stableLength).filter(isLive).map(m => String(m.content));
		const newestPolicy = [...stable].reverse().find(text => text.includes("[PI GOAL "));
		if (holding) {
			assert.ok(newestPolicy === undefined || /ON HOLD|begins "\[PI GOAL ON HOLD\]/.test(newestPolicy), `${tag}: on hold but the newest policy block is ${newestPolicy?.slice(0, 60)}`);
		} else if (fresh.state === GOAL_ENDED_STATE) {
			if (stable.length) assert.ok(newestPolicy?.includes("[PI GOAL ENDED]") || newestPolicy?.includes('begins "[PI GOAL ENDED]'), `${tag}: the goal ended but the newest policy block is ${newestPolicy?.slice(0, 60)}`);
		} else {
			const header = fresh.state.split("\n", 1)[0]!;
			assert.ok(newestPolicy !== undefined && (newestPolicy.includes(header) || newestPolicy.includes(`begins "${header}"`)), `${tag}: the newest policy block is not the current one (${newestPolicy?.slice(0, 70)} against ${header})`);
			if (fresh.counters) {
				const list = [...stable].reverse().find(text => text.startsWith("[TASK LIST") || text === TASK_LIST_NONE);
				assert.equal(list, fresh.counters, `${tag}: the newest task list is not the current one`);
			}
		}
		assert.ok((live.contents(key) ?? []).length <= MAX_RETAINED_LIVE_TAILS + MAX_RETAINED_POINTERS, `${tag}: too many retained blocks`);

		// What the provider is sent, and what its cache says.
		let payload = payloadFor(out.messages);
		payload = cacheGoalHistory(payload, live.contents(key)) ?? payload;
		const stableAtoms = atomsFor(payloadFor(out.messages.slice(0, out.stableLength)));
		const atoms = atomsFor(payload);

		const expectedPrefix = previous && !rewritten && !restartedNow && !corrupted && !edited && !decorating && !previousDecorated;
		if (previous && expectedPrefix) {
			assert.ok(sharedPrefix(previous.stableAtoms, atoms) === previous.stableAtoms.length, `${tag}: the prompt no longer starts with the stable part of the previous one (matches ${sharedPrefix(previous.stableAtoms, atoms)} of ${previous.stableAtoms.length}): ${atoms[sharedPrefix(previous.stableAtoms, atoms)]?.slice(0, 120)} | was ${previous.stableAtoms[sharedPrefix(previous.stableAtoms, atoms)]?.slice(0, 120)}`);
		}
		if (restartedNow && !rewritten && !corrupted) assert.match(live.restartInfo().last ?? "", /size limit|task list was removed/, `${tag}: unexpected restart`);

		const gap = previous ? now - previous.at : 0;
		const alive = previous ? gap < ttlMs : true;
		let record: any;
		if (spec.explicit) {
			const result = provider === "bedrock" || provider === "openrouter-anthropic" ? cache.processBlocks(explicitBlocks(provider, payload)) : cache.process(payload);
			assert.ok(!result.error, `${tag}: ${result.error}`);
			record = result.record;
			const u = result.usage;
			assert.equal(u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens, record.total, `${tag}: the token counts do not add up`);
			assert.ok(record.breakpoints.length <= 4, `${tag}: more than four breakpoints`);
			// The last breakpoint must sit on a block that comes back in the next request, not on request-only text.
			const lastBreakpoint = record.breakpoints.at(-1) as number | undefined;
			if (lastBreakpoint !== undefined && (live.contents(key)?.length ?? 0) > 0) assert.ok(lastBreakpoint < stableAtoms.length, `${tag}: the last breakpoint (block ${lastBreakpoint}) is on request-only text; the stable part is ${stableAtoms.length} blocks`);
			if (previous && previous.lastBreakpointBlock !== undefined) {
				const unchanged = atoms.length > previous.lastBreakpointBlock && sharedPrefix(previous.atoms, atoms) > previous.lastBreakpointBlock;
				const last = record.breakpoints.at(-1) as number | undefined;
				if (!alive) assert.equal(u.cache_read_input_tokens, 0, `${tag}: read ${u.cache_read_input_tokens} tokens after the entry expired (${Math.round(gap / 1000)} s)`);
				else if (unchanged && last !== undefined && last - previous.lastBreakpointBlock < cache.lookback) {
					assert.ok(u.cache_read_input_tokens >= previous.lastBreakpointTokens!, `${tag}: read ${u.cache_read_input_tokens} tokens, but ${previous.lastBreakpointTokens} were cached by the request before and the prefix is unchanged (breakpoint ${previous.lastBreakpointBlock} -> ${last})`);
				}
			}
		} else {
			const result = cache.process({ key: provider === "openai" || provider === "openai-completions" ? sessionKey : "", atoms });
			record = result.record;
			const read = record.read as number;
			assert.ok(read === 0 || ((read - cache.minTokens) % cache.increment === 0 && read >= cache.minTokens), `${tag}: a read of ${read} tokens is not a whole step`);
			assert.ok(read <= record.total, `${tag}: read more than the prompt`);
			if (previous) {
				if (!alive) assert.equal(read, 0, `${tag}: read ${read} tokens after the entry expired (${Math.round(gap / 1000)} s)`);
				else if (expectedPrefix && sharedPrefix(previous.stableAtoms, atoms) === previous.stableAtoms.length) {
					const prefixTokens = Math.floor(previous.stableAtoms.join("\n").length / cache.charsPerToken);
					const expected = prefixTokens < cache.minTokens ? 0 : cache.minTokens + cache.increment * Math.floor((prefixTokens - cache.minTokens) / cache.increment);
					assert.ok(read >= expected, `${tag}: read ${read} tokens, but the stable part of the request before is ${expected} (${prefixTokens} tokens)`);
				}
			}
		}
		log.push(`   request ok: read ${record.read ?? record.usage?.cache_read_input_tokens ?? "?"} of ${record.total}; tails=${live.contents(key)?.length}`);

		let lastBreakpointTokens: number | undefined;
		let lastBreakpointBlock: number | undefined;
		if (spec.explicit) {
			const last = record.breakpoints.at(-1);
			if (last !== undefined) {
				lastBreakpointBlock = last;
				lastBreakpointTokens = (record.blockTokens as number[]).slice(0, last + 1).reduce((sum, n) => sum + n, 0);
			}
		}
		previous = { stableAtoms, atoms, lastBreakpointTokens, lastBreakpointBlock, at: now };
		previousBase = baseJson;
		previousDecorated = decorating;
		save();
		rewritten = false;
		edited = false;
	};

	for (const [step, op] of ops.entries()) {
		log.push(`${step}:${op.t}${current ? `[${current.id} ${current.status} v${current.version} t${current.tasks}]` : ""}${decorating ? "+deco" : ""}${holding ? "+hold" : ""}`);
		switch (op.t) {
			case "grow": history.push(msg("user", `u${step}`), msg("assistant", `a${step}`)); break;
			case "tool": history.push(msg("assistant", [{ type: "toolCall", id: `c${step}`, name: "read", arguments: { path: "x" } }]), msg("toolResult", `result ${step}`, { toolCallId: `c${step}` })); break;
			case "parallel": {
				const count = 2 + (op.n % 3);
				history.push(msg("assistant", Array.from({ length: count }, (_, i) => ({ type: "toolCall", id: `p${step}-${i}`, name: "read", arguments: { path: `f${i}` } }))));
				for (let i = 0; i < count; i++) history.push(msg("toolResult", `parallel result ${step}-${i}`, { toolCallId: `p${step}-${i}` }));
				break;
			}
			case "huge": history.push(msg("assistant", [{ type: "toolCall", id: `h${step}`, name: "bash", arguments: { path: "big" } }]), msg("toolResult", filler(20 + (op.n % 280), step), { toolCallId: `h${step}` })); break;
			case "unicode": history.push(msg("user", `${UNICODE} ${step}`), msg("assistant", `${UNICODE} reply`)); break;
			case "image": history.push(msg("user", [{ type: "text", text: `look ${step}` }, { type: "image", data: base64(2 + (op.n % 30), step), mimeType: "image/png" }]), msg("assistant", "seen")); break;
			case "goal": current = { id: `g${++goals}`, version: 1, tasks: 0, status: "active" }; holding = false; break;
			case "pause": if (current?.status === "active") current.status = "paused"; break;
			case "resume": if (current?.status === "paused") current.status = "active"; break;
			case "tasks": if (current && current.status !== "ended") current.tasks = op.r < 0.2 ? 0 : current.tasks + 1; break;
			case "end": if (current) current.status = "ended"; break;
			case "objective": if (current && current.status !== "ended") current.version++; break;
			case "decorate": decorating = !decorating; break;
			case "hold": holding = true; break;
			case "unhold": holding = false; break;
			case "compact": {
				if (history.length < 4) break;
				const keep = history.slice(-Math.max(2, Math.floor(history.length / 3)));
				// Keep a tool batch whole.
				while (keep[0]?.role === "toolResult") keep.shift();
				history = [{ role: "compactionSummary", content: `summary ${step}`, timestamp: clock++ }, ...keep];
				rewritten = true;
				break;
			}
			case "branch": {
				if (history.length < 3) break;
				let cut = 1 + Math.floor(op.r * (history.length - 1));
				// Never cut inside a tool batch.
				while (cut < history.length && history[cut]?.role === "toolResult") cut++;
				history = [...history.slice(0, cut), msg("user", `branch ${step}`)];
				rewritten = true;
				break;
			}
			case "edit": {
				if (history.length < 3) break;
				const i = Math.floor(op.r * (history.length - 1));
				if (typeof history[i].content === "string") { history[i] = { ...history[i], content: `${history[i].content} (edited ${step})` }; edited = true; }
				break;
			}
			case "bulk":
				if (history.length < 6) break;
				history = history.map(m => typeof m.content === "string" ? { ...m, content: `${m.content} (bulk ${step})` } : m);
				rewritten = true;
				break;
			case "clock": {
				const ttl = ttlMs;
				const choices = [1000, 30_000, ttl - 1000, ttl + 1000, 2 * ttl, 100 * ttl];
				now += choices[op.n % choices.length]!;
				break;
			}
			case "crash": crashAfter = op.n % 3; break;
			case "corrupt": {
				if (!entries.length) break;
				const i = Math.floor(op.r * entries.length);
				const kind = op.n % 6;
				const entry = entries[i]!;
				if (kind === 0) entries.splice(i, 1);
				else if (kind === 1) entries.splice(i, 0, JSON.parse(JSON.stringify(entry)));
				else if (kind === 2) entry.data = null;
				else if (kind === 3) entry.data = { ...(entry.data as object), text: "garbled \u0000 text", prefixHash: "nope" };
				else if (kind === 4) { const j = Math.floor(rand01(op.n) * entries.length); [entries[i], entries[j]] = [entries[j]!, entries[i]!]; }
				else entry.data = { v: 1, model, op: "tail", anchorIndex: -5, kind: "goal-state", text: 42, prefixHash: 7 };
				corrupted = true;
				break;
			}
			case "restart": {
				// A new process: nothing in memory, the saved entries and the same history.
				const unchanged = savedHistory === JSON.stringify(view());
				const hadBlocks = live.has(key);
				if (process.env.FUZZ_ENTRIES) log.push(`   entries: ${entries.map(e => (e.data as any).op + ((e.data as any).anchorIndex ?? '')).join(' ')}; saved=${live.saved.get(key)?.slice(0, 20)}`);
				const next = new LiveTailRetention();
				try { restoreLiveTails(next, key, model, entries, view()); } catch (error) { assert.fail(`${provider} seed ${seed} step ${step} (restart): restoring threw ${error}`); }
				const ok = next.has(key);
				const clean = failedSaves === 0 || savesSinceFailure > 0;
				if (unchanged && hadBlocks && !corrupted && clean) {
					assert.ok(ok, `${provider} seed ${seed} step ${step} (restart): nothing was restored although the history is the one saved`);
					const strip = (state: any) => JSON.parse(JSON.stringify({ ...state, generation: 0 }));
					assert.deepEqual(strip(next.exportState(key)), strip(live.exportState(key)), `${provider} seed ${seed} step ${step} (restart): what was restored is not what was live`);
				}
				if (hadBlocks && !ok) rewritten = true;
				// A restore that may be stale (changed history, a failed save or damaged entries) is allowed to differ from what was live.
				if (ok && (!hadBlocks || !unchanged || corrupted || !clean)) rewritten = true;
				live = next;
				break;
			}
			case "request": break;
		}
		if (op.t === "request" || op.r > 0.7 && !["clock", "crash", "corrupt", "decorate", "hold", "unhold"].includes(op.t)) request(step, op.t);
	}
	// Always finish with a request, so the last operations are checked too.
	request(ops.length, "final");
	void calls;
}

function rand01(n: number): number { return random(n)(); }

/** Remove operations while the walk still fails the same way. */
export function shrink(ops: Op[], options: WalkOptions): Op[] {
	const signature = (error: unknown): string => String((error as Error)?.message ?? error).replace(/seed \d+ step \d+/g, "seed S step N").replace(/\d+/g, "#").split("\n", 1)[0]!;
	const failure = (candidate: Op[]): string | undefined => { try { execute(candidate, { ...options, log: [] }); return undefined; } catch (error) { return signature(error); } };
	const target = failure(ops);
	if (target === undefined) return ops;
	let current = ops;
	let chunk = Math.ceil(current.length / 2);
	while (chunk >= 1) {
		let reduced = false;
		for (let start = 0; start < current.length; start += chunk) {
			const candidate = [...current.slice(0, start), ...current.slice(start + chunk)];
			if (candidate.length && failure(candidate) === target) { current = candidate; reduced = true; start -= chunk; }
		}
		if (!reduced) chunk = Math.floor(chunk / 2);
	}
	return current;
}

/** Run one walk, and on failure say how to replay it and which operations are enough to reproduce it. */
export function runWalk(provider: ProviderName, seed: number, steps: number): void {
	const ops = generate(seed, steps);
	const log: string[] = [];
	try {
		execute(ops, { provider, seed, log });
	} catch (error) {
		const small = shrink(ops, { provider, seed });
		const replay = `replay: FUZZ_PROVIDER=${provider} FUZZ_FROM=${seed} FUZZ_TO=${seed} FUZZ_STEPS=${steps}`;
		throw new Error(`${(error as Error).message}\n${replay}\nshrunk to ${small.length} of ${ops.length} operations: ${small.map(op => op.t).join(" ")}\n${JSON.stringify(small)}`);
	}
}
