import { describe, it, before, after, beforeEach, afterEach } from "node:test";
import assert from "node:assert/strict";
import * as path from "node:path";
import * as fs from "node:fs";
import type { MockPi } from "../support/helpers.ts";
import {
	createMockPi,
	createTempDir,
	removeTempDir,
	makeAgentConfigs,
	makeAgent,
	makeMinimalCtx,
	events,
	tryImport,
} from "../support/helpers.ts";

const utils = await tryImport<any>("./src/shared/utils.ts");
const execution = await tryImport<any>("./src/runs/foreground/execution.ts");
const childToolPlan = await tryImport<any>("./src/runs/shared/child-tool-plan.ts");

const piAvailable = !!(execution && utils);

const runSync = execution?.runSync;
const detectSubagentError = utils?.detectSubagentError;

describe("detectSubagentError", { skip: !detectSubagentError ? "utils not importable" : undefined }, () => {
	it("returns no error for successful messages", () => {
		const messages = [
			{ role: "assistant", content: [{ type: "text", text: "Let me check..." }] },
			{ role: "toolResult", toolName: "bash", isError: false, content: [{ type: "text", text: "OK" }] },
			{ role: "assistant", content: [{ type: "text", text: "All good!" }] },
		];
		const result = detectSubagentError(messages);
		assert.equal(result.hasError, false);
	});

	it("detects bash error in last tool result", () => {
		const messages = [
			{ role: "assistant", content: [{ type: "text", text: "Running..." }] },
			{
				role: "toolResult",
				toolName: "bash",
				isError: true,
				content: [{ type: "text", text: "command not found" }],
			},
		];
		const result = detectSubagentError(messages);
		assert.equal(result.hasError, true);
		assert.equal(result.errorType, "bash");
	});

	it("extracts a non-zero exit code from bash error output", () => {
		const messages = [
			{ role: "assistant", content: [{ type: "text", text: "Running..." }] },
			{
				role: "toolResult",
				toolName: "bash",
				isError: true,
				content: [{ type: "text", text: "Error: process exited with code 127" }],
			},
		];
		const result = detectSubagentError(messages);
		assert.equal(result.hasError, true);
		assert.equal(result.exitCode, 127);
	});

	it("ignores errors before last successful tool result", () => {
		const messages = [
			{ role: "assistant", content: [{ type: "text", text: "Trying..." }] },
			{ role: "toolResult", toolName: "bash", isError: true, content: [{ type: "text", text: "EISDIR" }] },
			{ role: "assistant", content: [{ type: "text", text: "Let me fix that..." }] },
			{ role: "toolResult", toolName: "bash", isError: false, content: [{ type: "text", text: "OK" }] },
			{ role: "assistant", content: [{ type: "text", text: "Fixed!" }] },
		];
		const result = detectSubagentError(messages);
		assert.equal(result.hasError, false);
	});

	it("detects isError on tool result", () => {
		const messages = [
			{ role: "assistant", content: [{ type: "text", text: "Running..." }] },
			{
				role: "toolResult",
				toolName: "write",
				isError: true,
				content: [{ type: "text", text: "Permission denied" }],
			},
		];
		const result = detectSubagentError(messages);
		assert.equal(result.hasError, true);
		assert.equal(result.errorType, "write");
	});
});

describe("runSync error handling", { skip: !piAvailable ? "pi packages not available" : undefined }, () => {
	let tempDir: string;
	let mockPi: MockPi;

	before(() => {
		mockPi = createMockPi();
		mockPi.install();
	});

	after(() => {
		mockPi.uninstall();
	});

	beforeEach(() => {
		tempDir = createTempDir();
		mockPi.reset();
	});

	afterEach(() => {
		removeTempDir(tempDir);
	});

	it("reports a child session failure as the run error", async () => {
		mockPi.onCall({ exitCode: 2, stderr: "Fatal: out of memory" });
		const agents = makeAgentConfigs(["crash"]);

		const result = await runSync(tempDir, agents, "crash", "Do heavy work", {});

		assert.equal(result.exitCode, 1);
		assert.ok(result.error?.includes("out of memory"));
	});

	it("detectSubagentError overrides exit 0 on hidden failure", async () => {
		mockPi.onCall({
			jsonl: [
				events.assistantMessage("Starting deployment"),
				events.toolStart("bash", { command: "deploy" }),
				events.toolEnd("bash"),
				events.toolResult("bash", "connection refused", true),
			],
		});
		const agents = makeAgentConfigs(["deployer"]);

		const result = await runSync(tempDir, agents, "deployer", "Deploy app", {});

		assert.notEqual(result.exitCode, 0, "should detect hidden failure");
		assert.ok(result.error?.includes("connection refused"));
	});

	it("fails a zero-exit child that stops during a tool after earlier assistant output", async () => {
		mockPi.onCall({
			jsonl: [
				events.assistantMessage("Work is in progress"),
				events.toolStart("bash", { command: "write files" }),
			],
			exitCode: 0,
		});
		const agents = makeAgentConfigs(["worker"]);

		const result = await runSync(tempDir, agents, "worker", "Do work", {});

		assert.equal(result.exitCode, 1);
		assert.match(result.error ?? "", /ended during 'bash' tool execution before the tool completed/);
		assert.match(result.error ?? "", /Earlier assistant output is not a terminal result/);
		assert.doesNotMatch(result.error ?? "", /cold-start/);
	});

	it("keeps a terminal answer authoritative over an earlier tool timeout", async () => {
		mockPi.onCall({
			steps: [
				{ jsonl: [events.toolStart("bash")] },
				{ delay: 50, jsonl: [events.assistantMessage("Done")] },
			],
			keepAliveAfterFinalMessageMs: 1_500,
		});
		const agents = makeAgentConfigs(["worker"]);

		const result = await runSync(tempDir, agents, "worker", "Do work", {
			toolTimeoutMs: 600,
			timeoutMs: 5_000,
		});

		assert.equal(result.exitCode, 0);
		assert.equal(result.timedOut, undefined);
		assert.equal(result.finalOutput, "Done");
	});

	it("kills a wedged foreground tool at the configured per-tool timeout", { skip: process.platform === "win32" ? "timeout signal delivery intermittent on Windows CI" : undefined }, async () => {
		mockPi.onCall({
			steps: [
				{ jsonl: [events.toolStart("bash")] },
				{ delay: 30_000 },
			],
		});
		const agents = makeAgentConfigs(["slow"]);

		const result = await runSync(tempDir, agents, "slow", "Wait", {
			toolTimeoutMs: 1_000,
			timeoutMs: 8_000,
		});

		assert.equal(result.timedOut, true);
		assert.match(result.error ?? "", /Tool 'bash' exceeded its timeout of 1000ms\./);
		assert.match(result.finalOutput ?? "", /^Tool 'bash' exceeded its timeout of 1000ms\.\n\nRecovery summary:/);
		assert.doesNotMatch(result.finalOutput ?? "", /Subagent timed out after/);
	});

	it("reports a foreground tool timeout without a run timeout as the tool timeout", { skip: process.platform === "win32" ? "timeout signal delivery intermittent on Windows CI" : undefined }, async () => {
		mockPi.onCall({
			steps: [
				{ jsonl: [events.toolStart("bash")] },
				{ delay: 30_000 },
			],
		});
		const agents = makeAgentConfigs(["slow"]);

		const result = await runSync(tempDir, agents, "slow", "Wait", { toolTimeoutMs: 1_000 });

		assert.equal(result.timedOut, true);
		assert.equal(result.error, "Tool 'bash' exceeded its timeout of 1000ms.");
		assert.match(result.finalOutput ?? "", /^Tool 'bash' exceeded its timeout of 1000ms\.\n\nRecovery summary:/);
		assert.doesNotMatch(result.finalOutput ?? "", /timed out after 0ms/);
	});

	it("keeps the tool timeout as the cause when a child ignores abort past the run deadline", { timeout: 15_000 }, async () => {
		let abortCalls = 0;
		const factory = {
			async create() {
				let listener: (event: { type: string; [key: string]: unknown }) => void = () => {};
				return {
					subscribe(handler: typeof listener) { listener = handler; return () => {}; },
					async prompt() {
						listener({ type: "tool_execution_start", toolCallId: "call-1", toolName: "bash", args: { command: "sleep 100" } });
						await new Promise(() => {});
					},
					async steer() {}, async followUp() {}, async dispose() {},
					async abort() { abortCalls++; },
					messages: [], sessionFile: undefined, sessionId: "ignores-abort", modelId: "mock/model",
				};
			},
			async dispose() {},
		};

		const result = await runSync(tempDir, makeAgentConfigs(["slow"]), "slow", "Wait", {
			toolTimeoutMs: 300,
			timeoutMs: 800,
			childSessionFactory: factory,
		});

		assert.equal(result.timedOut, true);
		assert.equal(result.error, "Tool 'bash' exceeded its timeout of 300ms.");
		assert.match(result.finalOutput ?? "", /^Tool 'bash' exceeded its timeout of 300ms\.\n\nRecovery summary:/);
		assert.equal(abortCalls, 1);
	});

	it("emits foreground open-tool attention for an earlier overlapping tool", async () => {
		mockPi.onCall({
			steps: [
				{ jsonl: [{ type: "tool_execution_start", toolCallId: "bash-1", toolName: "bash", args: { command: "sleep 2" } }] },
				{ delay: 50, jsonl: [
					{ type: "tool_execution_start", toolCallId: "read-1", toolName: "read", args: { path: "README.md" } },
					{ type: "tool_execution_end", toolCallId: "read-1", toolName: "read" },
				] },
				{ delay: 1_200, jsonl: [
					{ type: "tool_execution_end", toolCallId: "bash-1", toolName: "bash" },
					events.toolResult("bash", "done"),
					events.assistantMessage("Done"),
				] },
			],
		});
		const agents = makeAgentConfigs(["slow"]);
		const controlEvents: Array<{ type?: string; reason?: string; currentTool?: string; message?: string }> = [];

		const result = await runSync(tempDir, agents, "slow", "Wait", {
			runId: "foreground-overlap-attention",
			controlConfig: { enabled: true, needsAttentionAfterMs: 999_999, activeNoticeAfterMs: 100, notifyOn: ["needs_attention"] },
			onControlEvent: (event: { type?: string; reason?: string; currentTool?: string; message?: string }) => controlEvents.push(event),
		});

		const attention = controlEvents.find((event) => event.reason === "tool_open_threshold");
		assert.equal(result.exitCode, 0);
		assert.equal(attention?.type, "needs_attention");
		assert.equal(attention?.currentTool, "bash");
		assert.match(attention?.message ?? "", /tool 'bash' open/);
	});

	it("still emits open-tool attention when the child's command state cannot be read", async () => {
		mockPi.onCall({ steps: [
			{ jsonl: [{ type: "tool_execution_start", toolCallId: "long", toolName: "bash", args: { command: "sleep 2" } }] },
			{ delay: 1600, jsonl: [{ type: "tool_execution_end", toolCallId: "long", toolName: "bash" }, events.toolResult("bash", "done"), events.assistantMessage("Done")] },
		] });
		const runId = "foreground-unreadable-command-state";
		const channelDir = childToolPlan.supervisorChannelDir(runId, "worker", 0);
		fs.mkdirSync(channelDir, { recursive: true });
		// A truncated file makes the 1 s activity timer's read throw.
		fs.writeFileSync(path.join(channelDir, "commands.json"), "{");
		const notices: Array<{ reason?: string; hasCommandController?: boolean }> = [];
		const warnings: Array<{ message: string; key: string }> = [];
		try {
			const result = await runSync(tempDir, makeAgentConfigs(["worker"]), "worker", "Run a command", {
				runId,
				controlConfig: { enabled: true, needsAttentionAfterMs: 999_999, activeNoticeAfterMs: 100, notifyOn: ["needs_attention"] },
				onControlEvent: (event: { reason?: string; hasCommandController?: boolean }) => notices.push(event),
				onWarning: (message: string, key: string) => warnings.push({ message, key }),
			});
			assert.equal(result.exitCode, 0);
			assert.deepEqual(notices.filter((event) => event.reason === "tool_open_threshold").map((event) => event.hasCommandController), [false]);
			assert.equal(warnings.length, 1);
			assert.match(warnings[0]!.message, /Could not read the command state of worker/);
		} finally {
			fs.rmSync(channelDir, { recursive: true, force: true });
		}
	});

	it("emits attention once per long-open foreground call after an earlier attention state", async () => {
		mockPi.onCall({ steps: [
			{ jsonl: [{ type: "tool_execution_start", toolCallId: "first", toolName: "bash", args: { command: "sleep 2" } }] },
			{ delay: 1600, jsonl: [{ type: "tool_execution_end", toolCallId: "first", toolName: "bash" }, events.toolResult("bash", "done")] },
			{ jsonl: [{ type: "tool_execution_start", toolCallId: "second", toolName: "bash", args: { command: "sleep 2" } }] },
			{ delay: 1600, jsonl: [{ type: "tool_execution_end", toolCallId: "second", toolName: "bash" }, events.toolResult("bash", "done"), events.assistantMessage("Done")] },
		] });
		const notices: Array<{ reason?: string; toolCallId?: string }> = [];
		const result = await runSync(tempDir, makeAgentConfigs(["worker"]), "worker", "Run commands", {
			runId: "foreground-sequential-attention",
			controlConfig: { enabled: true, needsAttentionAfterMs: 999_999, activeNoticeAfterMs: 100, notifyOn: ["needs_attention"] },
			onControlEvent: (event: { reason?: string; toolCallId?: string }) => notices.push(event),
		});
		assert.equal(result.exitCode, 0);
		assert.deepEqual(notices.filter((event) => event.reason === "tool_open_threshold").map((event) => event.toolCallId), ["first", "second"]);
	});

	it("emits attention once for each overlapping long-open foreground call", async () => {
		mockPi.onCall({ steps: [
			{ jsonl: [{ type: "tool_execution_start", toolCallId: "first", toolName: "bash", args: { command: "sleep 3" } }] },
			{ delay: 50, jsonl: [{ type: "tool_execution_start", toolCallId: "second", toolName: "bash", args: { command: "sleep 3" } }] },
			{ delay: 2600, jsonl: [
				{ type: "tool_execution_end", toolCallId: "first", toolName: "bash" },
				{ type: "tool_execution_end", toolCallId: "second", toolName: "bash" },
				events.toolResult("bash", "done"),
				events.assistantMessage("Done"),
			] },
		] });
		const notices: Array<{ reason?: string; toolCallId?: string }> = [];
		const result = await runSync(tempDir, makeAgentConfigs(["worker"]), "worker", "Run commands", {
			runId: "foreground-overlapping-attention",
			controlConfig: { enabled: true, needsAttentionAfterMs: 999_999, activeNoticeAfterMs: 100, notifyOn: ["needs_attention"] },
			onControlEvent: (event: { reason?: string; toolCallId?: string }) => notices.push(event),
		});
		assert.equal(result.exitCode, 0);
		assert.deepEqual(notices.filter((event) => event.reason === "tool_open_threshold").map((event) => event.toolCallId), ["first", "second"]);
	});

	it("handles abort signal (completes faster than delay)", async () => {
		mockPi.onCall({ steps: [
			{ jsonl: [events.toolStart("bash", { command: "wait" })] },
			{ delay: 10000 },
		] });
		const agents = makeAgentConfigs(["slow"]);
		const controller = new AbortController();

		const start = Date.now();
		setTimeout(() => controller.abort(), 200);

		const result = await runSync(tempDir, agents, "slow", "Slow task", {
			signal: controller.signal,
		});
		const elapsed = Date.now() - start;

		assert.ok(elapsed < 5000, `should abort early, took ${elapsed}ms`);
		assert.doesNotMatch(result.error ?? "", /exited during 'bash' tool execution/);
	});
});
