import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { normalizePublicSubagentExecution } from "../../src/extension/public-execution.ts";

describe("public subagent execution normalization", () => {
	it("accepts structured single-child, workflow, management, and schedules", () => {
		assert.deepEqual(normalizePublicSubagentExecution({ workflowScript: "return 1", globalConcurrencyLimit: 4, maxSubagentSpawnsPerRun: 8 }), { ok: true, params: { workflowScript: "return 1", globalConcurrencyLimit: 4, maxSubagentSpawnsPerRun: 8 } });
		assert.deepEqual(normalizePublicSubagentExecution({ workflowScript: "return args.task", args: { task: "review" } }), { ok: true, params: { workflowScript: "return args.task", args: { task: "review" } } });
		assert.deepEqual(normalizePublicSubagentExecution({ workflow: "review", args: { task: "Review this" } }), { ok: true, params: { workflow: "review", args: { task: "Review this" } } });
		assert.deepEqual(normalizePublicSubagentExecution({ workflow: "parallel", args: { tasks: [] }, globalConcurrencyLimit: 1 }), { ok: true, params: { workflow: "parallel", args: { tasks: [] }, globalConcurrencyLimit: 1 } });
		assert.deepEqual(normalizePublicSubagentExecution({ workflowScript: "return 1", preflight: { version: 1, lanes: [] } }), { ok: true, params: { workflowScript: "return 1", preflight: { version: 1, lanes: [] } } });
		assert.deepEqual(normalizePublicSubagentExecution({ workflow: "workflows/review.js", globalConcurrencyLimit: 2 }), { ok: true, params: { workflow: "workflows/review.js", globalConcurrencyLimit: 2 } });
		assert.deepEqual(normalizePublicSubagentExecution({ workflow: "workflows/review.js", args: { task: "review" } }), { ok: true, params: { workflow: "workflows/review.js", args: { task: "review" } } });
		assert.deepEqual(normalizePublicSubagentExecution({ workflow: true, maxSubagentSpawnsPerRun: 8, preflight: { version: 1, lanes: [] } }), { ok: true, params: { workflow: true, maxSubagentSpawnsPerRun: 8, preflight: { version: 1, lanes: [] } } });
		const task = "Use `quotes`\nand newlines";
		assert.deepEqual(normalizePublicSubagentExecution({ agent: " worker ", task, context: "fresh", async: false }), {
			ok: true,
			params: {
				agent: "worker",
				task,
				context: "fresh",
				async: false,
				output: true,
			},
		});
		assert.deepEqual(normalizePublicSubagentExecution({ agent: "worker" }), {
			ok: true,
			params: {
				agent: "worker",
				output: true,
			},
		});
		assert.deepEqual(normalizePublicSubagentExecution({ agent: "worker", async: true, baseRef: "@/foo" }), {
			ok: true,
			params: {
				agent: "worker",
				async: true,
				baseRef: "@/foo",
				output: true,
			},
		});
		assert.deepEqual(normalizePublicSubagentExecution({ agent: "worker", output: false }), {
			ok: true,
			params: {
				agent: "worker",
				output: false,
			},
		});
		assert.deepEqual(normalizePublicSubagentExecution({ agent: "worker", isolation: "none" }), {
			ok: true,
			params: {
				agent: "worker",
				worktree: false,
				output: true,
			},
		});
		assert.deepEqual(normalizePublicSubagentExecution({ action: " list " }), { ok: true, params: { action: "list" } });
		assert.deepEqual(normalizePublicSubagentExecution({ action: " list ", capabilities: true }), { ok: true, params: { action: "list", capabilities: true } });
		assert.deepEqual(
			normalizePublicSubagentExecution({ action: " validate ", workflowScript: "return args.task", args: { task: "review" } }),
			{ ok: true, params: { action: "validate", workflowScript: "return args.task", args: { task: "review" } } },
		);
		assert.deepEqual(
			normalizePublicSubagentExecution({ action: " validate ", workflow: "./workflow.js" }),
			{ ok: true, params: { action: "validate", workflow: "./workflow.js" } },
		);
		const windowsPath = { workflow: "C:\\ci\\sweep.js", preflight: { version: 1, coverage: "complete", lanes: [{ key: "main", mode: "mutation" }] } };
		assert.deepEqual(normalizePublicSubagentExecution(windowsPath), { ok: true, params: windowsPath }, "a Windows script path is a path, not a resource name");
		assert.deepEqual(
			normalizePublicSubagentExecution({ action: " validate ", workflowScript: "return 1", maxSubagentSpawnsPerRun: 5 }),
			{ ok: true, params: { action: "validate", workflowScript: "return 1", maxSubagentSpawnsPerRun: 5 } },
		);
		assert.deepEqual(
			normalizePublicSubagentExecution({ action: " schedule.create ", every: "1h", workflowScript: "return args.task", args: { task: "review" } }),
			{ ok: true, params: { action: "schedule.create", every: "1h", workflowScript: "return args.task", args: { task: "review" } } },
		);
		assert.deepEqual(
			normalizePublicSubagentExecution({ action: " schedule.create ", every: "1h", workflow: true }),
			{ ok: true, params: { action: "schedule.create", every: "1h", workflow: true } },
		);
	});

	it("rejects unsafe base refs at the public boundary", () => {
		for (const baseRef of ["refs/heads/unsafe..ref", "branch name", "HEAD^{tree}", "@", "a".repeat(40), "a".repeat(64), 42]) {
			const result = normalizePublicSubagentExecution({ agent: "worker", baseRef });
			assert.equal(result.ok, false, String(baseRef));
			if (!result.ok) assert.match(result.error, /baseRef.*HEAD.*named ref.*40\/64-character commit IDs.*revision expressions.*unsupported/);
		}
	});

	it("rejects base refs on management actions that do not consume them", () => {
		const result = normalizePublicSubagentExecution({ action: "list", baseRef: "refs/heads/release" });
		assert.equal(result.ok, false);
		if (!result.ok) assert.match(result.error, /baseRef is only supported/);
	});

	it("accepts base refs on resume because resume consumes them", () => {
		assert.deepEqual(normalizePublicSubagentExecution({ action: " resume ", id: "run-1", message: "Continue", baseRef: "refs/heads/release" }), {
			ok: true,
			params: { action: "resume", id: "run-1", message: "Continue", baseRef: "refs/heads/release" },
		});
	});

	it("rejects the removed workflowScriptPath field and names the path form", () => {
		const result = normalizePublicSubagentExecution({ workflowScriptPath: "workflow.js" });
		assert.equal(result.ok, false);
		if (!result.ok) assert.match(result.error, /workflowScriptPath was removed.*workflow: "\.\/path\/to\/script\.js"/);
	});

	it("rejects named workflow combinations and caller-controlled provenance fields", () => {
		for (const params of [
			{ workflow: "review", workflowScript: "return 1" },
			{ workflow: true, workflowScript: "return 1" },
			{ workflow: "review", agent: "worker" },
			{ workflow: true, agent: "worker" },
			{ workflow: false },
			{ workflow: "review", preflight: { version: 1, lanes: [] } },
			{ action: "validate", workflow: "review" },
			{ workflow: "review", task: "work" },
			{ args: { task: "work" } },
			{ workflow: "review", resource: { kind: "workflow" } },
			{ workflow: "review", resourceProvenance: { kind: "workflow" } },
			{ workflow: "review", workflowResourcePermit: {} },
		] as const) {
			const result = normalizePublicSubagentExecution(params);
			assert.equal(result.ok, false, JSON.stringify(params));
		}
	});

	it("rejects bare arguments and arguments on direct child launches", () => {
		for (const params of [{ args: {} }, { agent: "worker", task: "work", args: {} }] as const) {
			const result = normalizePublicSubagentExecution(params);
			assert.equal(result.ok, false);
			if (!result.ok) assert.match(result.error, /args requires workflow/);
		}
	});

	it("rejects options.reuseFrom without a workflow", () => {
		for (const params of [{ reuseFrom: "run-1" }, { agent: "worker", task: "work", reuseFrom: "run-1" }] as const) {
			const result = normalizePublicSubagentExecution(params);
			assert.deepEqual(result, { ok: false, error: "options.reuseFrom requires a workflow launch.", mode: "workflow" });
		}
	});

	it("keeps raw workflow inputs untrusted and rejects invalid named-resource arguments", () => {
		const raw = normalizePublicSubagentExecution({ workflowScript: `return await runs.host("ci", { kind: "command", command: "npm test", timeoutMs: 1000 });` });
		assert.equal(raw.ok, true);
		if (raw.ok) assert.equal(Object.hasOwn(raw.params, "resource"), false);
		for (const params of [
			{ args: { task: "work" } },
			{ workflow: "", args: {} },
			{ workflow: 42, args: {} },
		] as const) {
			const result = normalizePublicSubagentExecution(params);
			assert.equal(result.ok, false, JSON.stringify(params));
		}
	});

	it("rejects preflight without a workflow input", () => {
		const result = normalizePublicSubagentExecution({ agent: "worker", preflight: { version: 1, lanes: [] } });
		assert.equal(result.ok, false);
		if (!result.ok) assert.match(result.error, /preflight requires workflow: true or a workflow script path/);
	});

	it("rejects private run fan-out fields at the public boundary", () => {
		for (const params of [
			{ workflowScript: "return 1", runFanoutBudget: { version: 1 } },
			{ workflowScript: "return 1", runFanoutAdmitted: true },
		] as const) {
			const result = normalizePublicSubagentExecution(params);
			assert.equal(result.ok, false);
			if (!result.ok) assert.match(result.error, /does not accept internal run fan-out fields/);
		}
	});

	it("rejects private workflow child fields at the public boundary", () => {
		for (const params of [
			{ agent: "worker", workflowParentRunId: "workflow" },
			{ agent: "worker", workflowKey: "child" },
			{ agent: "worker", workflowChildAsyncId: "child" },
			{ agent: "worker", workflowAwaitAsync: true },
			{ agent: "worker", workflowAwaitDetached: true },
			{ agent: "worker", workflowParentDeadlineAt: Date.now() + 1_000 },
			{ agent: "worker", suppressRoutineResultIntercom: true },
		] as const) {
			const result = normalizePublicSubagentExecution(params);
			assert.equal(result.ok, false);
			if (!result.ok) assert.match(result.error, /internal workflow child fields/);
		}
	});

	it("rejects mixed, invalid, and removed public execution shapes", () => {
		for (const params of [
			{ action: " " },
			{ action: "single" },
			{ action: "parallel" },
			{ action: "chain" },
			{ action: "append-step", id: "run", step: { agent: "worker" } },
			{ action: "approve-checkpoint", id: "run" },
			{ action: "reject-checkpoint", id: "run" },
			{ agent: "" },
			{ agent: 42 },
			{ task: "work" },
			{ agent: "worker", task: 42 },
			{ agent: "worker", workflowScript: "return 1" },
			{ action: "status", task: "work" },
			{ tasks: [{ agent: "worker" }] },
			{ chain: [{ agent: "worker" }] },
			{ parallel: [{ agent: "worker" }] },
			{ concurrency: 2 },
			{ action: "get", chainName: "review-pipeline" },
			{ action: "create", config: { name: "review-pipeline", steps: [{ agent: "worker" }] } },
			{ clarify: true, workflowScript: "return 1" },
			{ resume: "retained-run", workflowScript: "return 1" },
			{},
			{ workflowScript: " " },
			{ workflowScriptPath: " " },
			{ action: "status", workflowScript: "return 1" },
			{ action: "schedule.create", every: "1h", agent: "worker", workflowScript: "return 1" },
			{ workflowScript: "return 1", isolation: "invalid" },
			{ workflowScript: "return 1", isolation: "none", worktree: true },
			{ workflowScript: "return 1", isolation: "worktree", worktree: false },
			{ agent: "worker", globalConcurrencyLimit: 2 },
			{ workflow: "review", maxSubagentSpawnsPerRun: 2 },
			{ action: "validate", workflowScript: "return 1", globalConcurrencyLimit: 2 },
			{ workflowScript: "return 1", globalConcurrencyLimit: 0 },
			{ workflowScript: "return 1", maxSubagentSpawnsPerRun: 1.5 },
			{ workflowScript: "return 1", maxSubagentSpawnsPerRun: Number.MAX_SAFE_INTEGER + 1 },
		] as const) {
			assert.equal(normalizePublicSubagentExecution(params).ok, false, JSON.stringify(params));
		}
	});
});
