import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { test } from 'vitest';
import { fileURLToPath } from "node:url";

const __dirname = dirname(fileURLToPath(import.meta.url));
const subagentSrc = readFileSync(join(__dirname, "..", "index.ts"), "utf-8");
const manifestSrc = readFileSync(
	join(__dirname, "..", "extension-manifest.json"),
	"utf-8",
);

test("SubagentParams declares optional background field", () => {
	const paramsStart = subagentSrc.indexOf(
		"const SubagentParams = Type.Object({",
	);
	const paramsEnd = subagentSrc.indexOf("});", paramsStart);
	const paramsBlock = subagentSrc.slice(paramsStart, paramsEnd);
	assert.match(paramsBlock, /background:\s*Type\.Optional\(\s*Type\.Boolean/);
});

test("subagent execute registers background jobs and disables nested background flag", () => {
	assert.match(
		subagentSrc,
		/if \(params\.background\)/,
		"subagent tool should branch on params.background",
	);
	assert.match(
		subagentSrc,
		/manager\.register\(\s*summarizeBackgroundInvocation\(params\)/,
		"background path should register a job",
	);
	assert.match(
		subagentSrc,
		/params:\s*\{\s*\.\.\.params,\s*confirmProjectAgents:\s*false,\s*background:\s*false,\s*\}/,
		"background execution should clear background on the nested invocation",
	);
});

test("subagent extension registers await_subagent and cancel_subagent tools", () => {
	assert.match(subagentSrc, /name:\s*"await_subagent"/);
	assert.match(subagentSrc, /name:\s*"cancel_subagent"/);
});

test("extension manifest advertises background subagent tools and lifecycle hooks", () => {
	assert.match(manifestSrc, /"await_subagent"/);
	assert.match(manifestSrc, /"cancel_subagent"/);
	assert.match(manifestSrc, /"session_start"/);
	assert.match(manifestSrc, /"session_before_switch"/);
});
