/**
 * Random sequences of goal tools, commands, reloads and restarts against the real extension,
 * with rules that must hold after every step: nothing throws, the goals on disk match the ones
 * in memory, task lists stay well formed, and a restart brings the same goal back.
 * Scale up with FUZZ_FROM, FUZZ_TO and FUZZ_STEPS; a failure names the seed and the steps.
 */
import test from "node:test";
import assert from "node:assert/strict";
import { mkdirSync, rmSync } from "node:fs";
import path from "node:path";
import { tempDir } from "./support/fs.ts";
import { createExtensionHarness } from "./support/extension-harness.ts";
import { readActiveGoalPool } from "../extensions/storage/goal-files.ts";
import { random } from "./support/cache-walk.ts";

const FROM = Number(process.env.FUZZ_FROM ?? 1);
const TO = Number(process.env.FUZZ_TO ?? 30);
const STEPS = Number(process.env.FUZZ_STEPS ?? 40);

const STATUSES = new Set(["active", "paused", "blocked", "budget_limited", "complete"]);
const TASK_STATUSES = new Set(["pending", "in_progress", "complete", "skipped", "completed", "started"]);
const approved = { approved: true, disapproved: false, output: "ok\n<approved/>", model: "mock" };
const disapproved = { approved: false, disapproved: true, output: "no\n<disapproved/>", model: "mock" };

function flatten(tasks: any[] | undefined, out: any[] = []): any[] {
	for (const task of tasks ?? []) { out.push(task); flatten(task.subtasks, out); }
	return out;
}

type Op = { t: string; r: number; n: number };
const OPS = ["create", "create", "tasks", "task", "task", "task", "pause", "resume", "block", "complete", "turn", "get", "focus", "unfocus", "status", "clear", "reload", "restart", "direct", "audit"];

function generate(seed: number, steps: number): Op[] {
	const rand = random(seed);
	return Array.from({ length: steps }, () => ({ t: OPS[Math.floor(rand() * OPS.length)]!, r: rand(), n: Math.floor(rand() * 1000) }));
}

/** Run the operations against a fresh project. Throws on the first broken rule. */
async function execute(ops: Op[], seed: number, log: string[] = []): Promise<void> {
	const cwd = tempDir("goal-lifecycle-fuzz-");
	mkdirSync(path.join(cwd, ".pi", "goals", "archived"), { recursive: true });
	const sessionId = `fuzz-${seed}`;
	let audit = approved;
	// The session file: what earlier processes appended, then what this one appends.
	let carried: unknown[] = [];
	const options = (restarted: boolean) => ({ cwd, hasUI: false, sessionId, runCompletionAuditor: async () => audit, ...(restarted ? { sessionEntries: () => [...carried, ...h.entries] } : {}) });
	let h = createExtensionHarness(options(false));
	/** Tool replies are read by the model: they must not leak internals. */
	const call = async (name: string, params: unknown) => {
		const result: any = await h.callTool(name, params);
		const text = (result?.content ?? []).map((block: any) => block?.text ?? "").join("\n");
		assert.doesNotMatch(text, /undefined|\[object Object\]|NaN|Infinity/, `${name} replied with a leaked value: ${text.slice(0, 200)}`);
		return result;
	};
	try {
		await h.sessionStart();
		for (const [step, { t: op, r, n }] of ops.entries()) {
			const before = h.core.state.goal ? { id: h.core.state.goal.id, status: h.core.state.goal.status } : undefined;
			log.push(`${step}:${op}${before ? `[${before.id.slice(-4)} ${before.status}]` : ""}`);
			const ids = flatten(h.core.state.goal?.taskList?.tasks).map(task => task.id);
			const choose = <T>(items: readonly T[]): T => items[n % items.length]!;
			switch (op) {
				case "create": await call("create_goal", { objective: `Objective ${step}: ${"do the thing ".repeat(1 + (n % 4))}` }); break;
				case "direct": await h.runCommand("goal-direct", `Direct objective ${step}`); break;
				case "tasks": await call("set_goal_tasks", { tasks: Array.from({ length: 1 + (n % 4) }, (_, i) => ({ id: `t${i}`, title: `Task ${i} of step ${step}`, ...(r < 0.3 ? { subtasks: [{ id: `t${i}s`, title: `Sub ${i}` }] } : {}) })), block_completion: r < 0.5 }); break;
				case "task": await call("update_goal_task", { task_id: r < 0.15 ? "nope" : choose([...ids, "t0", "t1"]), status: choose(["start", "complete", "skipped", "pending"] as const), evidence: "checked", reason: "user said so" }); break;
				case "pause": await call("update_goal", { status: "paused", reason: "fuzz" }); break;
				case "resume": await h.runCommand("goal-resume"); break;
				case "block": await call("update_goal", { status: "blocked", reason: "fuzz" }); break;
				case "complete": await call("update_goal", { status: "complete" }); await h.emit("turn_end", { message: { role: "assistant", stopReason: "stop", usage: { input: 0, output: 0 } } }); break;
				case "turn": await h.emit("turn_end", { message: { role: "assistant", stopReason: "stop", usage: { input: 10, output: 10 } } }); break;
				case "get": await call("get_goal", {}); break;
				case "focus": await h.runCommand("goal-focus"); break;
				case "unfocus": await h.runCommand("goal-unfocus"); break;
				case "status": await h.runCommand("goal-status", "verbose"); break;
				case "clear": await h.runCommand("goal-clear"); break;
				case "audit": audit = audit === approved ? disapproved : approved; break;
				case "reload": await h.sessionStart("reload"); break;
				case "restart": {
					const goal = h.core.state.goal;
					const snapshot = goal ? JSON.stringify({ id: goal.id, objective: goal.objective, tasks: flatten(goal.taskList?.tasks).map(t => [t.id, t.status]) }) : undefined;
					carried = [...carried, ...h.entries];
					delete (globalThis as any)[Symbol.for("pi-goal-x.liveRetention")];
					h = createExtensionHarness(options(true));
					await h.sessionStart("resume");
					const now = h.core.state.goal;
					if (goal && goal.status !== "complete" && snapshot && now) {
						assert.equal(JSON.stringify({ id: now.id, objective: now.objective, tasks: flatten(now.taskList?.tasks).map(t => [t.id, t.status]) }), snapshot, "a restart changed the focused goal");
					}
					break;
				}
			}

			// Rules after every step.
			const goal = h.core.state.goal;
			if (goal) {
				assert.ok(STATUSES.has(goal.status), `unknown status ${goal.status}`);
				const all = flatten(goal.taskList?.tasks);
				assert.equal(new Set(all.map(task => task.id)).size, all.length, "task ids are not unique");
				for (const task of all) assert.ok(TASK_STATUSES.has(task.status), `unknown task status ${task.status}`);
				assert.ok((goal.usage?.tokensUsed ?? 0) >= 0, "negative token use");
			}
			const pool = readActiveGoalPool({ cwd });
			for (const record of pool.values()) {
				assert.ok(STATUSES.has(record.status), `unknown status on disk ${record.status}`);
				assert.notEqual(record.status, "complete", "a completed goal is still in the active folder");
			}
			if (goal && goal.status !== "complete") {
				const onDisk = pool.get(goal.id);
				assert.ok(onDisk, `the focused goal ${goal.id} is not on disk`);
				assert.equal(onDisk!.objective, goal.objective, "objective on disk differs from memory");
				assert.equal(onDisk!.status, goal.status, "status on disk differs from memory");
			}
		}
	} finally {
		rmSync(cwd, { recursive: true, force: true });
	}
}

/** Remove operations while the walk still fails the same way. */
async function shrink(ops: Op[], seed: number): Promise<Op[]> {
	const signature = (error: unknown): string => String((error as Error)?.message ?? error).split("\n", 1)[0]!.replace(/\d+/g, "#");
	const failure = async (candidate: Op[]): Promise<string | undefined> => { try { await execute(candidate, seed); return undefined; } catch (error) { return signature(error); } };
	const target = await 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 && await failure(candidate) === target) { current = candidate; reduced = true; start -= chunk; }
		}
		if (!reduced) chunk = Math.floor(chunk / 2);
	}
	return current;
}

async function walk(seed: number): Promise<void> {
	const ops = generate(seed, STEPS);
	const log: string[] = [];
	try {
		await execute(ops, seed, log);
	} catch (error) {
		const small = await shrink(ops, seed);
		throw new Error(`seed ${seed}: ${(error as Error)?.stack ?? error}\nshrunk to ${small.length} of ${ops.length} operations: ${small.map(op => op.t).join(" ")}\n${JSON.stringify(small)}`);
	}
}

for (let seed = FROM; seed <= TO; seed++) test(`goal lifecycle walk, seed ${seed}`, { timeout: 60000 }, () => walk(seed));
