import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { formatWatchdogOrchestrationActivity, formatWatchdogReviewMessage, formatWatchdogSupervisorReplies, formatWatchdogTurnDelta } from "../../src/watchdog/turn-delta.ts";
import { SUBAGENT_WATCHDOG_WARNING_TYPE } from "../../src/watchdog/types.ts";

describe("watchdog turn delta formatter", () => {
	it("formats user prompt, assistant text, thinking, tool calls, and tool results", () => {
		const delta = formatWatchdogTurnDelta({
			includeUserPrompt: true,
			userPrompt: "Implement the parser.",
			messages: [
				{
					role: "assistant",
					content: [
						{ type: "text", text: "I will inspect the settings." },
						{ type: "thinking", thinking: "The settings parser is the risky part." },
						{ type: "toolCall", name: "bash", arguments: { command: "printf 'a\\nb'" } },
					],
				},
			],
			events: [
				{
					type: "tool_execution_end",
					toolName: "bash",
					result: { content: [{ type: "text", text: "a\nb" }] },
					isError: false,
				},
			],
		});

		assert.match(delta, /User prompt:\nImplement the parser\./);
		assert.match(delta, /Assistant:\nI will inspect the settings\./);
		assert.match(delta, /Thinking:\nThe settings parser is the risky part\./);
		assert.match(delta, /Tool call: bash\nArguments:\ncommand:/);
		assert.match(delta, /printf 'a\\nb'/);
		assert.match(delta, /Tool result: bash\nResult:\na\nb/);
	});

	it("uses a successful tool diff instead of noisy raw edit blobs", () => {
		const delta = formatWatchdogTurnDelta({
			messages: [
				{
					role: "assistant",
					content: [{
						type: "toolCall",
						name: "edit",
						arguments: {
							path: "src/file.ts",
							oldText: "huge old text",
							newText: "huge new text",
							edits: [{ oldText: "nested old text", newText: "nested new text" }],
						},
					}],
				},
				{
					role: "toolResult",
					toolName: "edit",
					content: "oldText: huge\nnewText: huge",
					details: { diff: "--- a/file.ts\n+++ b/file.ts\n@@\n-old\n+new" },
					isError: false,
				},
			],
		});

		assert.match(delta, /Tool result: edit\nDiff:\n--- a\/file\.ts/);
		assert.match(delta, /oldText: \[omitted 13 chars; use tool result diff\]/);
		assert.match(delta, /newText: \[omitted 13 chars; use tool result diff\]/);
		assert.match(delta, /oldText: \[omitted 15 chars; use tool result diff\]/);
		assert.match(delta, /newText: \[omitted 15 chars; use tool result diff\]/);
		assert.doesNotMatch(delta, /huge old text/);
		assert.doesNotMatch(delta, /huge new text/);
		assert.doesNotMatch(delta, /nested old text/);
		assert.doesNotMatch(delta, /nested new text/);
		assert.doesNotMatch(delta, /oldText: huge/);
	});

	it("marks failed tool results from isError and does not replace them with diffs", () => {
		const delta = formatWatchdogTurnDelta({
			messages: [{ role: "toolResult", toolName: "edit", isError: true, content: [{ type: "text", text: "edit failed" }], details: { diff: "should not render" } }],
		});

		assert.match(delta, /Tool result: edit\nError: tool reported an error\nOutput:\nedit failed/);
		assert.doesNotMatch(delta, /should not render/);
	});

	it("formats turn_end events with assistant message and tool results", () => {
		const delta = formatWatchdogTurnDelta({
			events: [
				{
					 type: "turn_end",
					 message: {
						 role: "assistant",
						 content: [
							{ type: "text", text: "I will run a check." },
							{ type: "toolCall", name: "bash", arguments: { command: "npm test" } },
						 ],
					 },
					 toolResults: [
						 { role: "toolResult", toolName: "bash", isError: true, content: [{ type: "text", text: "tests failed" }] },
					 ],
				},
			],
		});

		assert.match(delta, /Assistant:\nI will run a check\./);
		assert.match(delta, /Tool call: bash\nArguments:\ncommand: npm test/);
		assert.match(delta, /Tool result: bash\nError: tool reported an error\nOutput:\ntests failed/);
	});

	it("filters watchdog warning custom messages from its own review stream", () => {
		const warningMessage = {
			role: "custom",
			customType: SUBAGENT_WATCHDOG_WARNING_TYPE,
			content: "prior watchdog warning",
		};

		assert.equal(formatWatchdogReviewMessage(warningMessage), undefined);
		assert.equal(formatWatchdogTurnDelta({ messages: [warningMessage] }), "");
	});

	it("marks final assistant stop when represented", () => {
		const delta = formatWatchdogTurnDelta({
			messages: [{ role: "assistant", content: "Done.", stopReason: "stop" }],
			finalAssistantStop: true,
		});

		assert.match(delta, /Assistant stop: stop/);
		assert.match(delta, /Final assistant stop: stop without tool call/);
	});

	it("distinguishes a validated structured terminal from an ordinary empty terminal", () => {
		const messages = [{ role: "assistant", content: [], stopReason: "stop" }];
		const ordinary = formatWatchdogTurnDelta({ messages, finalAssistantStop: true });
		const structured = formatWatchdogTurnDelta({ messages, finalAssistantStop: true, structuredTerminal: true });

		assert.match(ordinary, /Assistant: \(no text\)/);
		assert.match(ordinary, /stop without tool call/);
		assert.doesNotMatch(structured, /\(no text\)|stop without tool call/);
		assert.match(structured, /validated structured output is the terminal response; no prose is required/);
		assert.match(structured, /validated structured output completed the response/);
	});

	it("keeps independent tool evidence visible at a structured terminal", () => {
		const delta = formatWatchdogTurnDelta({
			structuredTerminal: true,
			messages: [
				{ role: "toolResult", toolName: "bash", isError: true, content: "tests failed" },
				{ role: "assistant", content: [], stopReason: "stop" },
			],
		});

		assert.match(delta, /Tool result: bash\nError: tool reported an error\nOutput:\ntests failed/);
		assert.match(delta, /validated structured output is the terminal response/);
	});

	it("counts subagent workflow launches in every workflow form as orchestration activity", () => {
		const calls = [{ workflow: true }, { workflow: "./ci/sweep.js" }, { workflow: "review" }, { workflowScript: "return 1" }]
			.map((args, index) => ({ type: "toolCall", id: `call-${index}`, name: "subagent", arguments: args }));
		const activity = formatWatchdogOrchestrationActivity({
			type: "turn_end",
			message: { content: calls },
			toolResults: calls.map((call) => ({ role: "toolResult", toolCallId: call.id, toolName: "subagent", content: [{ type: "text", text: `launched ${call.id}` }] })),
		});
		for (const id of ["call-0", "call-1", "call-2"]) assert.match(activity, new RegExp(`launched ${id}`));
		assert.doesNotMatch(activity, /launched call-3/);
	});

	it("counts launches and actions whose fields arrive inside args as orchestration activity", () => {
		const calls = [{ args: { agent: "probe", task: "Inspect" } }, { args: { action: "status" } }, { args: { workflow: "parallel", args: { tasks: [] } } }]
			.map((args, index) => ({ type: "toolCall", id: `call-${index}`, name: "subagent", arguments: args }));
		const activity = formatWatchdogOrchestrationActivity({
			type: "turn_end",
			message: { content: calls },
			toolResults: calls.map((call) => ({ role: "toolResult", toolCallId: call.id, toolName: "subagent", content: [{ type: "text", text: `launched ${call.id}` }] })),
		});
		for (const id of ["call-0", "call-1", "call-2"]) assert.match(activity, new RegExp(`launched ${id}`));
	});

	it("keeps only answered contact_supervisor decision and interview requests as supervisor replies", () => {
		const calls = [
			{ id: "decision", reason: "need_decision" },
			{ id: "interview", reason: "interview_request" },
			{ id: "progress", reason: "progress_update" },
			{ id: "failed", reason: "need_decision" },
			{ id: "unpaired", reason: "need_decision" },
		].map(({ id, reason }) => ({ type: "toolCall", id, name: "contact_supervisor", arguments: { reason, message: `ask ${id}` } }));
		const result = (id: string, extra: Record<string, unknown> = {}) => ({ role: "toolResult", toolCallId: id, toolName: "contact_supervisor", content: [{ type: "text", text: `reply ${id}` }], ...extra });
		const replies = formatWatchdogSupervisorReplies({
			type: "turn_end",
			message: { content: calls },
			toolResults: [result("decision"), result("interview"), result("progress"), result("failed", { isError: true }), result("other-id")],
		});
		assert.equal(replies.length, 2);
		assert.match(replies[0]!, /^Tool call: contact_supervisor[\s\S]*ask decision[\s\S]*Tool result: contact_supervisor\nResult:\nreply decision$/);
		assert.match(replies[1]!, /reply interview$/);
	});
});
