import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { readReplyWorkflowScript } from "../../src/extension/reply-workflow-script.ts";

const call = (id: string, args: Record<string, unknown> = { workflow: true }) => ({ type: "toolCall", id, name: "subagent", arguments: args });
const branch = (...content: unknown[]) => ({ getBranch: () => [{ type: "message", message: { role: "assistant", content } }] }) as never;

describe("reply workflow block", () => {
	it("returns the one tagged block from the reply that issued the call, exactly as written", () => {
		const script = "const note = `\n```js\n`;\n  return runs.run('main', { agent: 'worker' });";
		// The first fence only quotes the tag, so it is skipped; the tagged fence may use javascript and trailing spaces.
		const text = ["Plan:", "```md", "```js workflow", "```", "```javascript workflow  ", script, "```", "Done."].join("\n");
		assert.deepEqual(readReplyWorkflowScript(branch({ type: "text", text }, call("call-1")), "call-1"), { script });
	});

	it("runs a lone plain js block, and prefers the tagged block when the reply also has plain js examples", () => {
		assert.deepEqual(readReplyWorkflowScript(branch({ type: "text", text: "```js\nreturn 1;\n```" }, call("call-1")), "call-1"), { script: "return 1;" });
		const text = "```js\nexample();\n```\n```js workflow\nreturn 2;\n```";
		assert.deepEqual(readReplyWorkflowScript(branch({ type: "text", text }, call("call-1")), "call-1"), { script: "return 2;" });
	});

	it("does not count a sibling call that passes options.script alongside workflow: true (#3320)", () => {
		const manager = branch({ type: "text", text: "```js workflow\nreturn 1;\n```" }, call("call-1"), call("call-2", { workflow: true, options: { script: "return 2;" } }));
		assert.deepEqual(readReplyWorkflowScript(manager, "call-1"), { script: "return 1;" });
		// options.script: "null" is an unset placeholder, so that sibling reads the reply block too.
		const placeholder = readReplyWorkflowScript(branch({ type: "text", text: "```js workflow\nreturn 1;\n```" }, call("call-1"), call("call-2", { workflow: true, options: { script: "null" } })), "call-1");
		assert.ok("error" in placeholder && /2 subagent calls with workflow: true; a reply can carry only one/.test(placeholder.error), JSON.stringify(placeholder));
	});

	it("counts a workflow: true call whose fields arrive inside args toward the one-block limit", () => {
		const result = readReplyWorkflowScript(branch({ type: "text", text: "```js workflow\nreturn 1;\n```" }, call("call-1"), call("call-2", { args: { workflow: true } })), "call-1");
		assert.ok("error" in result && /2 subagent calls with workflow: true; a reply can carry only one/.test(result.error), JSON.stringify(result));
	});

	it("fails instead of guessing when the block or its owning call is ambiguous or missing", () => {
		const block = "```js workflow\nreturn 1;\n```";
		for (const [manager, pattern] of [
			[branch({ type: "text", text: "no block" }, call("call-1")), /exact line "```js workflow".*found 0\. If the block is in your reply: .*options: \{ script: "\.\.\." \} in place of workflow: true/],
			[branch({ type: "thinking", thinking: "```js workflow\nreturn 1;\n```" }, call("call-1")), /no text in the session, so no ```js workflow block reached it\. .*options: \{ script: "\.\.\." \} in place of workflow: true/],
			[branch({ type: "text", text: "```js\na();\n```\n```js\nb();\n```" }, call("call-1")), /found 0\. This reply has 2 untagged js blocks/],
			[branch({ type: "text", text: `${block}\n${block}` }, call("call-1")), /found 2/],
			[branch({ type: "text", text: "```js workflow\nreturn 1;" }, call("call-1")), /not closed/],
			[branch({ type: "text", text: block }, call("call-1"), call("call-2")), /2 subagent calls with workflow: true/],
			[branch({ type: "text", text: block }, call("other-call")), /only works from a model subagent tool call/],
		] as const) {
			const result = readReplyWorkflowScript(manager, "call-1");
			assert.ok("error" in result && pattern.test(result.error), JSON.stringify(result));
		}
	});

	it("names an earlier message of the turn that holds the block, without running it", () => {
		const message = (role: string, ...content: unknown[]) => ({ type: "message", message: { role, content } });
		const turn = { getBranch: () => [
			message("user", { type: "text", text: "go" }),
			message("assistant", { type: "text", text: "```js workflow\nreturn 1;\n```" }, { type: "toolCall", id: "write-1", name: "write", arguments: {} }),
			message("toolResult", { type: "text", text: "ok" }),
			message("assistant", call("call-1")),
		] } as never;
		const result = readReplyWorkflowScript(turn, "call-1");
		assert.ok("error" in result && /A ```js block is in an earlier message of this turn, but workflow: true reads only the message that issues the call\. Pass that script's source as options: \{ script: "\.\.\." \}/.test(result.error), JSON.stringify(result));
	});
});
