import assert from "node:assert/strict";
import { describe, it } from "node:test";
import type { AgentConfig } from "../../src/agents/agents.ts";
import { prepareWorkflowLaunchParams, promptAuditRedoParams, resolveRevivalControlConfig, resolveWorkflowChildLocalCwd, sanitizeRunPathSegment } from "../../src/runs/foreground/subagent-executor.ts";
import { resolveControlConfig } from "../../src/runs/shared/subagent-control.ts";

describe("workflow launch params", () => {
	it("keeps remote workflow cwd out of local discovery for explicit and agent-pinned machines", () => {
		const workflowCwd = "/local/workflow";
		const discoverCalls: string[] = [];
		const pinned: AgentConfig = {
			name: "pinned",
			description: "Pinned agent",
			systemPrompt: "Run remotely.",
			systemPromptMode: "replace",
			inheritProjectContext: false,
			inheritGlobalContext: false,
			inheritSkills: false,
			source: "project",
			filePath: "/local/workflow/.pi/agents/pinned.md",
			machine: "workmac",
		};
		const discoverAgents = (cwd: string) => {
			discoverCalls.push(cwd);
			return { agents: [pinned] };
		};
		const shared = { workflowCwd, discoverAgents, agents: [] as AgentConfig[] };

		assert.equal(resolveWorkflowChildLocalCwd({ ...shared, params: { agent: "worker", machine: "workmac", cwd: "/remote/repo" } }), workflowCwd);
		assert.deepEqual(discoverCalls, []);
		assert.equal(resolveWorkflowChildLocalCwd({ ...shared, params: { agent: "pinned", cwd: "/remote/repo" } }), workflowCwd);
		assert.deepEqual(discoverCalls, [workflowCwd]);
	});

	it("preserves omitted workflow child async defaults and awaits background resolution", () => {
		assert.deepEqual(
			prepareWorkflowLaunchParams(
				{},
				{ agent: "worker", task: "Run" },
				"workflow-run",
				"run",
			),
			{
				agent: "worker",
				task: "Run",
				workflowAwaitAsync: true,
				workflowParentRunId: "workflow-run",
				workflowKey: "run",
			},
		);
	});

	it("forwards workflow baseRef only to launches where it can affect allocation", () => {
		assert.equal(
			prepareWorkflowLaunchParams(
				{ baseRef: "refs/heads/release" },
				{ agent: "worker", task: "Run" },
				"workflow-run",
				"run",
			).baseRef,
			"refs/heads/release",
		);
		assert.equal(
			prepareWorkflowLaunchParams(
				{ baseRef: "refs/heads/release" },
				{ resume: "retained-run", task: "Continue" },
				"workflow-run",
				"resume",
			).baseRef,
			undefined,
		);
		assert.equal(
			prepareWorkflowLaunchParams(
				{ baseRef: "refs/heads/release" },
				{ resume: "retained-run", task: "Continue", baseRef: "refs/heads/topic" },
				"workflow-run",
				"resume-explicit",
			).baseRef,
			"refs/heads/topic",
		);
		assert.equal(
			prepareWorkflowLaunchParams(
				{ baseRef: "refs/heads/release" },
				{ agent: "worker", task: "Run", baseRef: "refs/heads/topic" },
				"workflow-run",
				"override",
			).baseRef,
			"refs/heads/topic",
		);
	});

	it("does not forward workflow capacity overrides to children", () => {
		const params = prepareWorkflowLaunchParams(
			{ globalConcurrencyLimit: 2, maxSubagentSpawnsPerRun: 3 },
			{ agent: "worker", task: "Run", globalConcurrencyLimit: 4, maxSubagentSpawnsPerRun: 5 },
			"workflow-run",
			"run",
		);
		assert.equal(params.globalConcurrencyLimit, undefined);
		assert.equal(params.maxSubagentSpawnsPerRun, undefined);
	});

	it("merges partial control overrides into workflow child defaults", () => {
		const params = prepareWorkflowLaunchParams(
			{ control: { needsAttentionAfterMs: 111, activeNoticeAfterMs: 222 } },
			{ agent: "worker", task: "Run", control: { activeNoticeAfterMs: 333 } },
			"workflow-run",
			"run",
		);

		assert.deepEqual(params.control, {
			needsAttentionAfterMs: 111,
			activeNoticeAfterMs: 333,
		});
	});

	it("marks only new async workflow children to preserve live supervisor-detach awaits", () => {
		// Retained workflow children already use the async result-file await path.
		assert.equal(prepareWorkflowLaunchParams(
			{},
			{ agent: "worker", task: "Run" },
			"workflow-run",
			"run",
			{ awaitDetachedChild: true },
		).workflowAwaitDetached, true);
		assert.equal(prepareWorkflowLaunchParams(
			{},
			{ resume: "retained-run", task: "Continue" },
			"workflow-run",
			"resume",
			{ awaitDetachedChild: true },
		).workflowAwaitDetached, undefined);
	});

	it("scrubs the live workflow detach bridge from prompt-audit redo params", () => {
		const workflowChild = prepareWorkflowLaunchParams(
			{},
			{ agent: "worker", task: "Run" },
			"workflow-run",
			"run",
			{ awaitDetachedChild: true },
		);
		assert.equal(workflowChild.workflowAwaitDetached, true);

		const redo = promptAuditRedoParams(workflowChild, "Run with narrower guidance");
		assert.equal(redo.workflowAwaitDetached, undefined);
		assert.equal(redo.workflowParentRunId, undefined);
		assert.equal(redo.workflowKey, undefined);
		assert.equal(redo.async, false);
		assert.equal(redo.task, "Run with narrower guidance");
	});

	it("passes an omitted child timeout parent deadline for default resolution", () => {
		const parentDeadlineAt = Date.now() + 60_000;
		const params = prepareWorkflowLaunchParams(
			{},
			{ agent: "worker", task: "Run" },
			"workflow-run",
			"run",
			{ parentDeadlineAt },
		);
		assert.equal(params.async, undefined);
		assert.equal(params.workflowAwaitAsync, true);
		assert.equal(params.timeoutMs, undefined);
		assert.equal(params.workflowParentDeadlineAt, parentDeadlineAt);
	});

	it("preserves explicit child timeout aliases over the parent deadline", () => {
		const parentDeadlineAt = Date.now() + 60_000;
		assert.equal(prepareWorkflowLaunchParams(
			{},
			{ agent: "worker", task: "Run", timeoutMs: 90_000 },
			"workflow-run",
			"timeout",
			{ parentDeadlineAt },
		).timeoutMs, 90_000);
		const maxRuntimeParams = prepareWorkflowLaunchParams(
			{},
			{ agent: "worker", task: "Run", maxRuntimeMs: 90_000 },
			"workflow-run",
			"max-runtime",
			{ parentDeadlineAt },
		);
		assert.equal(maxRuntimeParams.maxRuntimeMs, 90_000);
		assert.equal(maxRuntimeParams.timeoutMs, undefined);
	});

	it("preserves explicit async workflow children", () => {
		assert.deepEqual(
			prepareWorkflowLaunchParams(
				{},
				{ agent: "worker", task: "Run", async: true },
				"workflow-run",
				"run",
			),
			{
				agent: "worker",
				task: "Run",
				async: true,
				workflowParentRunId: "workflow-run",
				workflowKey: "run",
			},
		);
	});

	it("runs omitted external workflow children async while preserving awaited semantics", () => {
		assert.deepEqual(
			prepareWorkflowLaunchParams(
				{},
				{ agent: "gpt-pro", task: "Check weather" },
				"workflow-run",
				"weather",
				{ externalAsyncRequired: true },
			),
			{
				agent: "gpt-pro",
				task: "Check weather",
				async: true,
				workflowAwaitAsync: true,
				workflowParentRunId: "workflow-run",
				workflowKey: "weather",
			},
		);
		assert.deepEqual(
			prepareWorkflowLaunchParams(
				{},
				{ agent: "gpt-pro", task: "Check weather", async: true },
				"workflow-run",
				"weather",
				{ externalAsyncRequired: true },
			),
			{
				agent: "gpt-pro",
				task: "Check weather",
				async: true,
				workflowParentRunId: "workflow-run",
				workflowKey: "weather",
			},
		);
		assert.deepEqual(
			prepareWorkflowLaunchParams(
				{},
				{ agent: "gpt-pro", task: "Check weather", async: false },
				"workflow-run",
				"weather",
				{ externalAsyncRequired: true },
			),
			{
				agent: "gpt-pro",
				task: "Check weather",
				async: false,
				workflowParentRunId: "workflow-run",
				workflowKey: "weather",
			},
		);
	});

	it("keeps a bridge override scoped to the target workflow child", () => {
		assert.deepEqual(
			prepareWorkflowLaunchParams(
				{},
				{ agent: "worker", task: "Run", intercomBridge: { mode: "off" } },
				"workflow-run",
				"isolated",
			),
			{
				agent: "worker",
				task: "Run",
				intercomBridge: { mode: "off" },
				workflowAwaitAsync: true,
				workflowParentRunId: "workflow-run",
				workflowKey: "isolated",
			},
		);
		assert.equal(prepareWorkflowLaunchParams({}, { agent: "worker", task: "Run" }, "workflow-run", "sibling").intercomBridge, undefined);
	});

	it("canonicalizes child extension bindings without leaking them to siblings", () => {
		const bindings = { "shepherd.dispatch/1": { writeScope: ["src/a.ts"], role: "coder" } };
		const child = prepareWorkflowLaunchParams({ extensionBindings: { "defaults.policy/1": true } }, { agent: "worker", task: "Run", extensionBindings: bindings }, "workflow-run", "bound");
		assert.deepEqual(child.extensionBindings, bindings);
		assert.equal(prepareWorkflowLaunchParams({}, { agent: "worker", task: "Run" }, "workflow-run", "plain").extensionBindings, undefined);
	});

	it("keeps managed worktree children on the single-run contract", () => {
		assert.deepEqual(
			prepareWorkflowLaunchParams(
				{},
				{ agent: "worker", task: "Implement", worktree: true, gate: "npm test" },
				"workflow-run",
				"gated",
			),
			{
				agent: "worker",
				task: "Implement",
				worktree: true,
				workflowAwaitAsync: true,
				workflowParentRunId: "workflow-run",
				workflowKey: "gated",
				acceptance: { level: "verified", verify: [{ id: "gate", command: "npm test" }] },
			},
		);
	});

	it("projects an object gate into a typed verify command", () => {
		const gate = { command: "classify.sh --report r.md", output: "json", schema: { type: "object" }, timeoutMs: 5000 };
		assert.deepEqual(
			prepareWorkflowLaunchParams({}, { agent: "reviewer", task: "Review", gate }, "workflow-run", "typed"),
			{
				agent: "reviewer",
				task: "Review",
				workflowAwaitAsync: true,
				workflowParentRunId: "workflow-run",
				workflowKey: "typed",
				acceptance: { level: "verified", verify: [{ id: "gate", command: "classify.sh --report r.md", output: "json", schema: { type: "object" }, timeoutMs: 5000 }] },
			},
		);
	});

	it("preserves a bridge override for retained workflow children", () => {
		assert.deepEqual(
			prepareWorkflowLaunchParams(
				{},
				{ resume: "retained-run", task: "Continue", intercomBridge: { mode: "off" } },
				"workflow-run",
				"continue",
			),
			{
				action: "resume",
				id: "retained-run",
				message: "Continue",
				workflowParentRunId: "workflow-run",
				workflowKey: "continue",
				intercomBridge: { mode: "off" },
			},
		);
	});

	it("forwards control defaults and overrides to retained workflow children", () => {
		assert.deepEqual(
			prepareWorkflowLaunchParams(
				{ control: { needsAttentionAfterMs: 111, activeNoticeAfterMs: 222 } },
				{ resume: "retained-run", task: "Continue", control: { activeNoticeAfterMs: 333 } },
				"workflow-run",
				"continue",
			),
			{
				action: "resume",
				id: "retained-run",
				message: "Continue",
				workflowParentRunId: "workflow-run",
				workflowKey: "continue",
				control: {
					needsAttentionAfterMs: 111,
					activeNoticeAfterMs: 333,
				},
			},
		);
	});

	it("lets retained workflow child control overrides amend recovered control configs", () => {
		const recovered = resolveControlConfig(undefined, { needsAttentionAfterMs: 111, activeNoticeAfterMs: 222 });
		const control = resolveRevivalControlConfig({
			recoveryControlConfig: recovered,
			requestedControl: { activeNoticeAfterMs: 333, notifyChannels: [] },
		});

		assert.equal(control.needsAttentionAfterMs, 111);
		assert.equal(control.activeNoticeAfterMs, 333);
		assert.deepEqual(control.notifyChannels, []);
	});

	it("does not inherit parent deadlines for retained workflow children", () => {
		assert.deepEqual(
			prepareWorkflowLaunchParams(
				{},
				{ resume: "retained-run", task: "Continue" },
				"workflow-run",
				"continue",
				{ parentDeadlineAt: Date.now() + 60_000 },
			),
			{
				action: "resume",
				id: "retained-run",
				message: "Continue",
				workflowParentRunId: "workflow-run",
				workflowKey: "continue",
			},
		);
	});

	it("preserves worktree isolation for retained workflow children", () => {
		assert.deepEqual(
			prepareWorkflowLaunchParams(
				{},
				{ resume: "retained-run", task: "Continue", worktree: true },
				"workflow-run",
				"continue",
			),
			{
				action: "resume",
				id: "retained-run",
				message: "Continue",
				workflowParentRunId: "workflow-run",
				workflowKey: "continue",
				worktree: true,
			},
		);
	});

	it("rejects gate defaults on retained resume items", () => {
		assert.throws(
			() => prepareWorkflowLaunchParams(
				{ gate: "npm test" },
				{ resume: "retained-run", task: "Continue" },
				"workflow-run",
				"continue",
			),
			/gate is not supported with retained resume/,
		);
		assert.throws(
			() => prepareWorkflowLaunchParams(
				{},
				{ resume: "retained-run", task: "Continue", gate: "npm test" },
				"workflow-run",
				"continue",
			),
			/gate is not supported with retained resume/,
		);
	});

	it("rejects extension binding amendments on retained resume items", () => {
		assert.throws(() => prepareWorkflowLaunchParams(
			{ extensionBindings: { "defaults.policy/1": true } },
			{ resume: "retained-run", task: "Continue" },
			"workflow-run",
			"continue",
		), /original retained child binding/);
	});

	it("preserves execution limits and fan-out identity when routing retained resume items", () => {
		assert.deepEqual(
			prepareWorkflowLaunchParams(
				{ toolBudget: { hard: 12, block: ["read"] } },
				{
					resume: " retained-run ",
					task: "Continue carefully",
					maxRuntimeMs: 5_000,
					toolBudget: { soft: 2, hard: 4, block: "*" },
				},
				"workflow-run",
				"continue",
				{ missionDetached: true, runFanoutBudget: { version: 1, rootRunId: "root-run", directory: "/tmp/fanout", limit: 64, parentPath: "parent" } },
			),
			{
				action: "resume",
				id: "retained-run",
				message: "Continue carefully",
				workflowParentRunId: "workflow-run",
				workflowKey: "continue",
				runFanoutBudget: { version: 1, rootRunId: "root-run", directory: "/tmp/fanout", limit: 64, parentPath: "parent/workflow[continue]" },
				mission: false,
				timeoutMs: 5_000,
				toolBudget: { soft: 2, hard: 4, block: "*" },
			},
		);
	});

	describe("sanitizeRunPathSegment", () => {
		it("replaces Windows-invalid characters and trims separators", () => {
			assert.equal(sanitizeRunPathSegment("call_VfdHQygxGeL1L49ez04A4tf7|WtnJ9gVpB/jdQGWbnKhfMgDqPGUGmNw"), "call_VfdHQygxGeL1L49ez04A4tf7_WtnJ9gVpB_jdQGWbnKhfMgDqPGUGmNw");
			assert.equal(sanitizeRunPathSegment(":::path//sub?*<file>|name:::"), "path_sub_file_name");
			assert.equal(sanitizeRunPathSegment("   ___invalid___   "), "invalid");
		});

		it("falls back to unknown for empty or all-invalid strings", () => {
			assert.equal(sanitizeRunPathSegment(""), "unknown");
			assert.equal(sanitizeRunPathSegment("   "), "unknown");
			assert.equal(sanitizeRunPathSegment("???///|||"), "unknown");
		});

		it("bounds oversized segments to the maximum byte length", () => {
			const longId = "a".repeat(200);
			const sanitized = sanitizeRunPathSegment(longId, 120);
			assert.equal(sanitized.length, 120);
			assert.equal(Buffer.byteLength(sanitized, "utf-8"), 120);
			assert.equal(sanitized, "a".repeat(120));
		});
	});
});
