import assert from "node:assert/strict";
import * as fs from "node:fs";
import * as path from "node:path";
import { afterEach, describe, it } from "node:test";
import type { AsyncJobState, SubagentState } from "../../src/shared/types.ts";
import {
	buildNestedRouteIndex,
	createNestedRoute,
	hasLiveNestedDescendants,
	nestedSummaryFromAsyncStatus,
	parseNestedEventRecords,
	inheritedNestedParentAddressOf,
	inheritedNestedRouteOf,
	projectNestedEvents,
	updateAsyncJobNestedProjection,
	updateForegroundNestedProjection,
	writeNestedEvent,
} from "../../src/runs/shared/nested-events.ts";

const routes: Array<{ eventSink: string }> = [];

async function removeDirWithRetry(dir: string): Promise<void> {
	let lastError: unknown;
	for (let attempt = 0; attempt < 5; attempt++) {
		try {
			fs.rmSync(dir, { recursive: true, force: true });
			return;
		} catch (error) {
			lastError = error;
			await new Promise((resolve) => setTimeout(resolve, 10));
		}
	}
	throw lastError;
}

afterEach(async () => {
	for (const route of routes.splice(0)) {
		await removeDirWithRetry(path.dirname(route.eventSink));
	}
});

function trackRoute(rootRunId = "root-run") {
	const route = createNestedRoute(rootRunId);
	routes.push(route);
	return route;
}

function child(id: string, state: "queued" | "running" | "complete" | "failed" | "paused" | "rejected", ts: number, parentRunId = "root-run") {
	return {
		id,
		parentRunId,
		parentStepIndex: 1,
		depth: 1,
		path: [{ runId: parentRunId, stepIndex: 1 }],
		mode: "single" as const,
		state,
		agent: "reviewer",
		agents: ["reviewer"],
		startedAt: 10,
		lastUpdate: ts,
		steps: [{ agent: "leaf", status: state === "running" ? "running" as const : "complete" as const }],
	};
}

describe("nested route index", () => {
	it("indexes routes by root run id in a single directory scan", () => {
		const routeA = trackRoute("index-root-a");
		const routeB = trackRoute("index-root-b");

		const index = buildNestedRouteIndex();

		assert.equal(index.get("index-root-a")?.capabilityToken, routeA.capabilityToken);
		assert.equal(index.get("index-root-b")?.capabilityToken, routeB.capabilityToken);
		assert.equal(index.get("missing-root"), undefined);
	});

	it("keeps at most one route when a root run id has duplicate route dirs", () => {
		const first = trackRoute("dup-root");
		const second = trackRoute("dup-root");

		const index = buildNestedRouteIndex();

		// readdir order is not guaranteed, so the contract is deduplication: exactly
		// one route is indexed per root run id, not a specific winner.
		const indexed = index.get("dup-root");
		assert.ok(indexed, "expected one route for dup-root");
		const tokens = new Set([first.capabilityToken, second.capabilityToken]);
		assert.ok(tokens.has(indexed.capabilityToken), "indexed route must be one of the two created routes");
	});

	it("recovers a route from its index when the route file is missing", () => {
		const route = trackRoute("late-route-root");
		const routeFile = path.join(path.dirname(route.eventSink), "route.json");
		fs.rmSync(routeFile);

		assert.equal(buildNestedRouteIndex().get("late-route-root")?.capabilityToken, route.capabilityToken);
		assert.equal(JSON.parse(fs.readFileSync(routeFile, "utf-8")).capabilityToken, route.capabilityToken);
	});
});

describe("nested event route validation", () => {
	it("resolves nested parent addresses from the inherited child runtime", () => {
		assert.deepEqual(inheritedNestedParentAddressOf({
			nestedParent: {
				parentRunId: "nested-parent",
				parentChildIndex: 2,
				depth: 3,
				path: [
					{ runId: "root-run", stepIndex: 0, agent: "root-agent" },
					{ runId: "nested-parent", stepIndex: 2, agent: "nested-agent" },
				],
			},
		}), {
			parentRunId: "nested-parent",
			parentStepIndex: 2,
			depth: 3,
			path: [
				{ runId: "root-run", stepIndex: 0, agent: "root-agent" },
				{ runId: "nested-parent", stepIndex: 2, agent: "nested-agent" },
			],
		});
		assert.deepEqual(inheritedNestedParentAddressOf({ nestedParent: { parentRunId: "nested-parent", depth: 1, path: [] } }), {
			parentRunId: "nested-parent",
			depth: 1,
			path: [{ runId: "nested-parent" }],
		});
	});

	it("ignores unsafe nested parent ids and missing parents", () => {
		assert.equal(inheritedNestedParentAddressOf({ nestedParent: { parentRunId: "../unsafe", parentChildIndex: 2, depth: 1, path: [] } }), undefined);
		assert.equal(inheritedNestedParentAddressOf({}), undefined);
		assert.equal(inheritedNestedParentAddressOf(undefined), undefined);
	});

	it("resolves only matching contained routes from the inherited child runtime", () => {
		const route = trackRoute();
		assert.deepEqual(inheritedNestedRouteOf({ nestedRoute: route }), route);
		assert.equal(inheritedNestedRouteOf({}), undefined);

		const originalError = console.error;
		const logged: unknown[] = [];
		console.error = (...args: unknown[]) => { logged.push(args[1]); };
		try {
			assert.equal(inheritedNestedRouteOf({ nestedRoute: { ...route, capabilityToken: "wrong-token" } }), undefined);
		} finally {
			console.error = originalError;
		}
		assert.match(String(logged[0]), /capability token/);
	});
});

describe("nested event parsing and projection", () => {
	it("projects started, updated, and completed records into async and foreground parent state", () => {
		const route = trackRoute();
		writeNestedEvent(route, {
			type: "subagent.nested.started",
			ts: 100,
			parentRunId: "root-run",
			parentStepIndex: 1,
			child: { ...child("nested-a", "running", 100), model: "provider/gpt-5.6-luna:medium", thinking: "medium", steps: [{ agent: "leaf", status: "running", model: "provider/leaf", thinking: "low" }], children: [child("nested-grandchild", "running", 100, "nested-a")] },
		});
		writeNestedEvent(route, {
			type: "subagent.nested.updated",
			ts: 200,
			parentRunId: "root-run",
			parentStepIndex: 1,
			child: {
				...child("nested-a", "running", 200),
				currentTool: "read",
				runtimeAcknowledgedExtensions: { version: 1, source: "child-runtime", ids: ["ext.ok", "bad/path", "ext.ok"], omitted: 1 },
			},
		});
		writeNestedEvent(route, {
			type: "subagent.nested.completed",
			ts: 300,
			parentRunId: "root-run",
			parentStepIndex: 1,
			child: { ...child("nested-a", "complete", 300), runtimeAcknowledgedExtensions: { version: 1, source: "child-runtime", ids: ["ext.ok", "bad/path", "ext.ok"], omitted: 1 } },
		});

		const registry = projectNestedEvents(route);
		assert.equal(registry.children.length, 1);
		assert.equal(registry.children[0]?.id, "nested-a");
		assert.equal(registry.children[0]?.state, "complete");
		assert.equal(registry.children[0]?.steps?.[0]?.agent, "leaf");
		assert.equal(registry.children[0]?.model, "provider/gpt-5.6-luna:medium");
		assert.equal(registry.children[0]?.thinking, "medium");
		assert.equal(registry.children[0]?.steps?.[0]?.model, "provider/leaf");
		assert.equal(registry.children[0]?.steps?.[0]?.thinking, "low");
		assert.equal(registry.children[0]?.children?.[0]?.id, "nested-grandchild");
		assert.deepEqual(registry.children[0]?.runtimeAcknowledgedExtensions, {
			version: 1,
			source: "child-runtime",
			ids: ["ext.ok"],
			omitted: 1,
		});

		const job: AsyncJobState = {
			asyncId: "root-run",
			asyncDir: "/tmp/root-run",
			status: "running",
			nestedRoute: route,
			steps: [
				{ agent: "owner-0", status: "running", index: 0 },
				{ agent: "owner-1", status: "running", index: 1 },
			],
		};
		updateAsyncJobNestedProjection(job);
		assert.equal(job.nestedChildren?.[0]?.id, "nested-a");
		assert.equal(job.steps?.[1]?.children?.[0]?.id, "nested-a");

		const control: SubagentState["foregroundControls"] extends Map<string, infer T> ? T : never = {
			runId: "root-run",
			mode: "single",
			startedAt: 1,
			updatedAt: 1,
			nestedRoute: route,
		};
		updateForegroundNestedProjection(control);
		assert.equal(control.nestedChildren?.[0]?.id, "nested-a");
	});

	it("attaches root children to visible step slices by original step index", () => {
		const route = trackRoute();
		writeNestedEvent(route, {
			type: "subagent.nested.updated",
			ts: 100,
			parentRunId: "root-run",
			parentStepIndex: 3,
			child: { ...child("nested-visible", "running", 100), parentStepIndex: 3, path: [{ runId: "root-run", stepIndex: 3 }] },
		});
		const job: AsyncJobState = {
			asyncId: "root-run",
			asyncDir: "/tmp/root-run",
			status: "running",
			nestedRoute: route,
			steps: [
				{ agent: "owner-2", status: "running", index: 2 },
				{ agent: "owner-3", status: "running", index: 3 },
			],
		};

		updateAsyncJobNestedProjection(job);

		assert.equal(job.steps?.[0]?.children, undefined);
		assert.equal(job.steps?.[1]?.children?.[0]?.id, "nested-visible");
	});

	it("ignores corrupt, partial, wrong-token, duplicate, and stale records while preserving terminal state", () => {
		const route = trackRoute();
		fs.writeFileSync(path.join(route.eventSink, "0000000000001-corrupt.json"), "{not json", "utf-8");
		fs.writeFileSync(
			path.join(route.eventSink, "0000000000002-partial.jsonl"),
			`${JSON.stringify({
				type: "subagent.nested.started",
				ts: 50,
				rootRunId: route.rootRunId,
				parentRunId: "root-run",
				parentStepIndex: 1,
				capabilityToken: route.capabilityToken,
				child: child("partial-good", "running", 50),
			})}\n{"type":"subagent.nested.started"`,
			"utf-8",
		);
		writeNestedEvent(route, {
			type: "subagent.nested.completed",
			ts: 300,
			parentRunId: "root-run",
			parentStepIndex: 1,
			child: child("nested-terminal", "complete", 300),
		});
		fs.writeFileSync(path.join(route.eventSink, "0000000000400-stale.json"), `${JSON.stringify({
			type: "subagent.nested.updated",
			ts: 400,
			rootRunId: route.rootRunId,
			parentRunId: "root-run",
			parentStepIndex: 1,
			capabilityToken: route.capabilityToken,
			child: child("nested-terminal", "running", 100),
		})}\n`, "utf-8");
		fs.writeFileSync(path.join(route.eventSink, "0000000000500-wrong-token.json"), `${JSON.stringify({
			type: "subagent.nested.started",
			ts: 500,
			rootRunId: route.rootRunId,
			parentRunId: "root-run",
			parentStepIndex: 1,
			capabilityToken: "wrong",
			child: child("wrong-token", "running", 500),
		})}\n`, "utf-8");

		const registry = projectNestedEvents(route);
		assert.equal(registry.children.find((item) => item.id === "partial-good")?.state, "running");
		assert.equal(registry.children.find((item) => item.id === "nested-terminal")?.state, "complete");
		assert.equal(registry.children.some((item) => item.id === "wrong-token"), false);
		assert.equal(hasLiveNestedDescendants(registry.children), true);
	});

	it("detects live descendants attached to terminal step children", () => {
		assert.equal(hasLiveNestedDescendants([{
			...child("terminal-parent", "complete", 300),
			steps: [{
				agent: "owner-step",
				status: "complete",
				children: [{
					...child("running-step-child", "running", 310, "terminal-parent"),
					parentStepIndex: 0,
					path: [{ runId: "terminal-parent", stepIndex: 0 }],
				}],
			}],
		}]), true);
	});

	it("preserves rejected nested states across the event and registry boundary", () => {
		const route = trackRoute("rejected-root");
		writeNestedEvent(route, {
			type: "subagent.nested.completed",
			ts: 300,
			parentRunId: route.rootRunId,
			parentStepIndex: 0,
			child: {
				...child("rejected-child", "rejected", 300, route.rootRunId),
				parentStepIndex: 0,
				path: [{ runId: route.rootRunId, stepIndex: 0 }],
				steps: [{ agent: "leaf", status: "rejected" }],
			},
		});

		const registry = projectNestedEvents(route);
		assert.equal(registry.children[0]?.state, "rejected");
		assert.equal(registry.children[0]?.steps?.[0]?.status, "rejected");
		assert.equal(hasLiveNestedDescendants(registry.children), false);
	});

	it("accepts only complete numeric token usage at the nested event boundary", () => {
		const route = trackRoute();
		writeNestedEvent(route, {
			type: "subagent.nested.updated",
			ts: 100,
			parentRunId: "root-run",
			parentStepIndex: 1,
			child: { ...child("nested-valid-tokens", "running", 100), totalTokens: { input: 10, output: 15, total: 25, window: 30, windowPeak: 40 } },
		});
		fs.writeFileSync(path.join(route.eventSink, "0000000000200-invalid-tokens.json"), `${JSON.stringify({
			type: "subagent.nested.updated",
			ts: 200,
			rootRunId: route.rootRunId,
			parentRunId: "root-run",
			parentStepIndex: 1,
			capabilityToken: route.capabilityToken,
			child: { ...child("nested-invalid-tokens", "running", 200), totalTokens: { input: 1, output: "bad", total: 1 } },
		})}\n`, "utf-8");

		const registry = projectNestedEvents(route);

		assert.deepEqual(registry.children.find((item) => item.id === "nested-valid-tokens")?.totalTokens, { input: 10, output: 15, total: 25, window: 30, windowPeak: 40 });
		assert.equal(registry.children.find((item) => item.id === "nested-invalid-tokens")?.totalTokens, undefined);
	});

	it("parses only complete jsonl records", () => {
		const route = trackRoute();
		const records = parseNestedEventRecords(`${JSON.stringify({
			type: "subagent.nested.started",
			ts: 100,
			rootRunId: route.rootRunId,
			parentRunId: "root-run",
			parentStepIndex: 1,
			capabilityToken: route.capabilityToken,
			child: child("jsonl-good", "running", 100),
		})}\n{"type":"subagent.nested.started"`, route);
		assert.equal(records.length, 1);
		assert.equal(records[0]?.child.id, "jsonl-good");
	});


	it("sanitizes nested model bounds and thinking levels", () => {
		const route = trackRoute();
		writeNestedEvent(route, {
			type: "subagent.nested.updated",
			ts: 100,
			parentRunId: "root-run",
			parentStepIndex: 1,
			child: {
				...child("nested-model-bounds", "running", 100),
				model: "m".repeat(600),
				thinking: "turbo",
				steps: [{ agent: "leaf", status: "running", model: "worker", thinking: "xhigh" }],
			},
		});
		const summary = projectNestedEvents(route).children[0]!;
		assert.equal(summary.model?.length, 512);
		assert.equal(summary.thinking, undefined);
		assert.equal(summary.steps?.[0]?.thinking, "xhigh");
	});

	it("projects effective model and thinking from async status, including a single-step run", () => {
		const summary = nestedSummaryFromAsyncStatus({
			runId: "child-run",
			mode: "single",
			state: "running",
			startedAt: 1,
			steps: [
				{ agent: "worker", status: "running", model: "provider/worker", thinking: "high" },
			],
		}, "/tmp/child-run", { id: "child-run", parentRunId: "parent-run", depth: 1, mode: "single", ts: 2 });

		assert.equal(summary.model, "provider/worker");
		assert.equal(summary.thinking, "high");
		assert.equal(summary.steps?.[0]?.model, "provider/worker");
		assert.equal(summary.steps?.[0]?.thinking, "high");
	});

	it("sanitizes malformed process-terminal proofs in nested status summaries", () => {
		const summary = nestedSummaryFromAsyncStatus({
			runId: "child-run",
			mode: "single",
			state: "complete",
			startedAt: 1,
			processTerminal: { version: 1, state: "bogus", runId: "child-run", runnerProcessInstanceId: "runner-1" } as never,
			steps: [{
				agent: "worker",
				status: "complete",
				processTerminal: { version: 1, state: "observed", runId: "wrong-run", runnerProcessInstanceId: "runner-1" } as never,
			}],
		}, "/tmp/child-run", { id: "child-run", parentRunId: "parent-run", depth: 1, mode: "single", ts: 2 });

		assert.equal(summary.processTerminal?.state, "unknown");
		assert.equal(summary.processTerminal?.reason, "proof-write-failed");
		assert.equal(summary.steps?.[0]?.processTerminal?.state, "unknown");
		assert.equal(summary.steps?.[0]?.processTerminal?.reason, "proof-write-failed");
	});

	it("sanitizes runtime acknowledged extensions in nested status summaries", () => {
		const summary = nestedSummaryFromAsyncStatus({
			runId: "child-run",
			mode: "single",
			state: "complete",
			startedAt: 1,
			runtimeAcknowledgedExtensions: { version: 1, source: "child-runtime", ids: ["/Users/alice/.secret-extension", "ok-ext", "x".repeat(5000)], omitted: 0 } as never,
			steps: [{
				agent: "worker",
				status: "complete",
				runtimeAcknowledgedExtensions: { version: 1, source: "child-runtime", ids: ["C:/Users/alice/secret"], omitted: 0 } as never,
			}],
		}, "/tmp/child-run", { id: "child-run", parentRunId: "parent-run", depth: 1, mode: "single", ts: 2 });

		assert.deepEqual(summary.runtimeAcknowledgedExtensions?.ids, ["ok-ext"]);
		assert.equal(summary.steps?.[0]?.runtimeAcknowledgedExtensions, undefined);
	});

	it("removes evicted status files without replaying completed children", () => {
		const route = trackRoute();
		for (let index = 0; index < 1000; index++) {
			writeNestedEvent(route, {
				type: "subagent.nested.updated",
				ts: index + 1,
				parentRunId: "root-run",
				parentStepIndex: 1,
				child: child("nested-retained", "running", index + 1),
			});
		}
		writeNestedEvent(route, {
			type: "subagent.nested.completed",
			ts: 1001,
			parentRunId: "root-run",
			parentStepIndex: 1,
			child: child("nested-retained", "complete", 1001),
		});

		assert.equal(fs.readdirSync(route.eventSink).length, 1001);
		const firstProjection = projectNestedEvents(route);
		assert.equal(firstProjection.processedEvents.length, 1000);
		assert.equal(fs.readdirSync(route.eventSink).length, 1000);
		assert.equal(firstProjection.children[0]?.state, "complete");

		const secondProjection = projectNestedEvents(route);
		assert.deepEqual(secondProjection, firstProjection);
		assert.equal(secondProjection.children[0]?.state, "complete");
	});
});

describe("nested session-name projection", () => {
	it("keeps bounded root and step session names from async status", () => {
		const summary = nestedSummaryFromAsyncStatus({
			runId: "child-run",
			mode: "single",
			state: "running",
			startedAt: 1,
			steps: [{
				agent: "reviewer",
				sessionName: "reviewer: Inspect the changed auth middleware",
				status: "running",
			}],
		}, "/tmp/child-run", { id: "child-run", parentRunId: "root-run", depth: 1, ts: 1 });
		assert.equal(summary.sessionName, "reviewer: Inspect the changed auth middleware");
		assert.equal(summary.steps?.[0]?.sessionName, "reviewer: Inspect the changed auth middleware");
	});
});
