/**
 * Random walks through everything that can happen to a conversation and its goal,
 * checked against rules that must always hold. Each seed is a different walk; a
 * failure names the seed so it can be replayed (FUZZ_SEEDS and FUZZ_STEPS change
 * how many walks and how long).
 *
 * Rules, per request:
 * - the real messages come out unchanged and in order;
 * - no goal block sits between a tool call and its result;
 * - the newest policy block is the one for the current goal state, and the newest
 *   task list is the current one;
 * - unless the history was rewritten on purpose (compaction, a branch, many edits,
 *   a draft) or a size limit was hit, the goal blocks stay where they were, and
 *   with no edited message the request starts with the previous one;
 * - a process restart gives the same request as no restart, or starts clean only
 *   when the history changed since the last save;
 * - the retained blocks stay within their bounds, and repeating a request adds nothing.
 */
import test from "node:test";
import assert from "node:assert/strict";
import { GOAL_ENDED_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 { random } from "./support/cache-walk.ts";
import { isLive, sharedPrefix } from "./support/retention-helpers.ts";

const SEEDS = Number(process.env.FUZZ_SEEDS ?? 150);
const STEPS = Number(process.env.FUZZ_STEPS ?? 90);

interface Goal { id: string; version: number; tasks: number; status: "active" | "paused" | "blocked" | "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): { state: string; counters?: string; ephemeral?: string; scope?: string; interim?: boolean; onlyIfSent?: boolean } {
	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}` };
}

/** Each goal block with the number of real messages before it, in the part of the request that is kept. */
function anchorsOf(messages: any[], stableLength: number): Array<[string, number]> {
	const out: Array<[string, number]> = [];
	let real = 0;
	for (const message of messages.slice(0, stableLength)) {
		if (isLive(message)) out.push([String(message.content), real]);
		else real++;
	}
	return out;
}

const EXPECTED_RESTARTS = /size limit|task list was removed/;

function runWalk(seed: number): void {
	const rand = random(seed);
	const pick = <T>(items: readonly T[]): T => items[Math.floor(rand() * items.length)]!;
	const chance = (p: number) => rand() < p;

	let clock = 1;
	const msg = (role: string, text: string): any => ({ role, content: text, timestamp: clock++ });
	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 reference = new LiveTailRetention();
	let goals = 0;
	let current: Goal | undefined;
	let usage = 0;
	let decorating = false;
	let rewritten = false;
	let edited = false;
	let restored = false;
	let previous: { messages: any[]; stableLength: number; decorated: boolean } | undefined;
	let previousBase: any[] = [];
	let savedHistory: string | undefined;

	/** What Pi hands the extension: the history, with a note on the newest message when another extension adds one. */
	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 = () => {
		saveLiveTails(live, key, model, view(), (type, data) => entries.push({ type: "custom", customType: type, data }));
		savedHistory = JSON.stringify(view());
	};

	const request = (step: number, what: string) => {
		const tag = `seed ${seed} step ${step} (${what})`;
		usage++;
		const base = view();
		// More than two messages with new text at once counts as a rewrite.
		if (base.slice(0, previousBase.length).filter((m, i) => JSON.stringify(m) !== JSON.stringify(previousBase[i])).length > 2) rewritten = true;
		previousBase = base;
		const fresh = freshFor(current, usage);
		const before = live.restartInfo();
		const out = live.apply(key, base, fresh);
		const restartedNow = live.restartInfo().count > before.count;
		const ref = reference.apply(key, view(), fresh);

		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 (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`);
		assert.deepEqual(live.apply(key, base, fresh).messages, out.messages, `${tag}: repeating the request changed it`);
		if (restored) assert.deepEqual(out.messages, ref.messages, `${tag}: differs from a walk without a restart`);

		if (previous && !rewritten && !restartedNow) {
			const was = anchorsOf(previous.messages, previous.stableLength);
			const now = anchorsOf(out.messages, out.stableLength);
			assert.deepEqual(now.slice(0, was.length), was, `${tag}: goal blocks moved or changed with no rewrite`);
			if (!edited && !decorating && !previous.decorated) {
				assert.ok(sharedPrefix(previous.messages, out.messages) >= previous.stableLength, `${tag}: the request no longer starts with the previous one`);
			}
		}
		if (restartedNow && !rewritten) assert.match(live.restartInfo().last ?? "", EXPECTED_RESTARTS, `${tag}: unexpected restart`);

		save();
		previous = { messages: out.messages, stableLength: out.stableLength, decorated: decorating };
		rewritten = false;
		edited = false;
	};

	const log: string[] = [];
	try {
	for (let step = 0; step < STEPS; step++) {
		const action = pick(["grow", "grow", "grow", "tool", "request", "request", "goal", "goal", "pause", "resume", "tasks", "end", "objective", "decorate", "compact", "branch", "edit", "bulk", "draft", "restart"] as const);
		log.push(`${step}:${action}${current ? `[${current.id} ${current.status} v${current.version} t${current.tasks}]` : ""}${decorating ? "+deco" : ""}`);
		switch (action) {
			case "grow":
				history.push(msg("user", `u${step}`), msg("assistant", `a${step}`));
				break;
			case "tool":
				history.push({ role: "assistant", content: [{ type: "toolCall", id: `c${step}` }], timestamp: clock++ }, { role: "toolResult", toolCallId: `c${step}`, content: `result ${step}`, timestamp: clock++ });
				break;
			case "goal":
				current = { id: `g${++goals}`, version: 1, tasks: 0, status: "active" };
				break;
			case "pause": if (current?.status === "active") current.status = "paused"; break;
			case "resume": if (current?.status === "paused" || current?.status === "blocked") current.status = "active"; break;
			case "tasks": if (current && current.status !== "ended") current.tasks += chance(0.2) ? -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 "compact": {
				if (history.length < 4) break;
				const keep = history.slice(-Math.max(2, Math.floor(history.length / 3)));
				history = [{ role: "compactionSummary", content: `summary ${step}`, timestamp: clock++ }, ...keep];
				rewritten = true;
				break;
			}
			case "branch": {
				if (history.length < 3) break;
				history = [...history.slice(0, 1 + Math.floor(rand() * (history.length - 1))), msg("user", `branch ${step}`)];
				rewritten = true;
				break;
			}
			case "edit": {
				// An earlier message gets new text but stays the same message.
				if (history.length < 3) break;
				const i = Math.floor(rand() * (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 "draft":
				// A draft over a live goal clears the blocks and saves that.
				live.clear(key);
				reference.clear(key);
				save();
				rewritten = 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);
				const next = new LiveTailRetention();
				restoreLiveTails(next, key, model, entries, view());
				const ok = next.has(key);
				if (unchanged && hadBlocks) assert.ok(ok, `seed ${seed} step ${step} (restart): nothing was restored although the history is the one saved`);
				if (hadBlocks && !ok) rewritten = true;
				log.push(`   restart: restored=${ok} hadBlocks=${hadBlocks} unchanged=${unchanged} tails=${next.contents(key)?.length}`);
				live = next;
				// A restore after a rewrite may keep more than a walk that saw it (the blocks before the change are still valid), so only compare when nothing changed.
				restored = ok;
				if (!(ok && unchanged)) {
					reference = new LiveTailRetention();
					const state = ok ? live.exportState(key) : undefined;
					if (state) reference.adopt(key, state, view());
				}
				break;
			}
			case "request": break;
		}
		if (action === "request" || chance(0.7)) { request(step, action); log.push(`   request ok; tails=${live.contents(key)?.length}`); }
	}
	} catch (error) {
		if (process.env.FUZZ_LOG) console.error(log.join("\n"));
		throw error;
	}
}

for (let seed = 1; seed <= SEEDS; seed++) test(`cache walk, seed ${seed}`, () => runWalk(seed));

/** Sessions that share one retention must not affect each other: each gets what it would get alone. */
function runSharedWalk(seed: number): void {
	const rand = random(seed);
	const pick = <T>(items: readonly T[]): T => items[Math.floor(rand() * items.length)]!;
	const shared = new LiveTailRetention();
	const count = 2 + Math.floor(rand() * 4);
	const worlds = Array.from({ length: count }, (_, n) => ({ key: `session-${n}`, solo: new LiveTailRetention(), history: [{ role: "user", content: `start ${n}`, timestamp: 1 }] as any[], goal: undefined as Goal | undefined, clock: 2, usage: 0 }));
	for (let step = 0; step < 120; step++) {
		const w = pick(worlds);
		const action = pick(["grow", "tool", "goal", "pause", "resume", "tasks", "end", "objective", "clear"] as const);
		if (action === "grow") w.history.push({ role: "user", content: `u${step}`, timestamp: w.clock++ }, { role: "assistant", content: `a${step}`, timestamp: w.clock++ });
		else if (action === "tool") w.history.push({ role: "assistant", content: [{ type: "toolCall", id: `c${step}` }], timestamp: w.clock++ }, { role: "toolResult", toolCallId: `c${step}`, content: "r", timestamp: w.clock++ });
		else if (action === "goal") w.goal = { id: `g${step}`, version: 1, tasks: 0, status: "active" };
		else if (action === "pause" && w.goal?.status === "active") w.goal.status = "paused";
		else if (action === "resume" && w.goal?.status === "paused") w.goal.status = "active";
		else if (action === "tasks" && w.goal && w.goal.status !== "ended") w.goal.tasks++;
		else if (action === "end" && w.goal) w.goal.status = "ended";
		else if (action === "objective" && w.goal && w.goal.status !== "ended") w.goal.version++;
		else if (action === "clear") { shared.clear(w.key); w.solo.clear(w.key); }
		const fresh = freshFor(w.goal, ++w.usage);
		const a = shared.apply(w.key, w.history.map(m => ({ ...m })), fresh);
		const b = w.solo.apply(w.key, w.history.map(m => ({ ...m })), fresh);
		assert.deepEqual(a.messages, b.messages, `seed ${seed} step ${step} (${action}) ${w.key}: another session changed this one's request`);
	}
}

for (let seed = 1; seed <= Math.max(20, Math.floor(SEEDS / 5)); seed++) test(`sessions sharing one retention stay apart, seed ${seed}`, () => runSharedWalk(seed));

test("the busiest of many sessions keeps its blocks while idle ones are evicted", () => {
	const retention = new LiveTailRetention();
	const history = [{ role: "user", content: "start", timestamp: 1 }] as any[];
	const goal: Goal = { id: "main", version: 1, tasks: 0, status: "active" };
	const first = retention.apply("main", history, freshFor(goal, 1));
	for (let n = 0; n < 60; n++) {
		retention.apply(`idle-${n}`, [{ role: "user", content: "x", timestamp: 1 }], freshFor({ ...goal, id: `idle-${n}` }, 1));
		history.push({ role: "assistant", content: `a${n}`, timestamp: 2 + n });
		const out = retention.apply("main", history, freshFor(goal, n + 2));
		assert.deepEqual(out.messages.slice(0, first.stableLength), first.messages.slice(0, first.stableLength), `main lost its blocks after ${n + 1} other sessions`);
	}
});
