import assert from "node:assert/strict";
import { mkdtemp, readFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { spawnSync } from "node:child_process";
import test from "node:test";

const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const hasPi = spawnSync("pi", ["--version"], { encoding: "utf8" }).status === 0;

test("all package extensions load together without global registration conflicts", { skip: !hasPi }, async () => {
	const packageJson = JSON.parse(await readFile(join(repositoryRoot, "package.json"), "utf8")) as {
		pi: { extensions: string[] };
	};
	const home = await mkdtemp(join(tmpdir(), "my-pi-extension-load-"));
	const args = ["--no-extensions"];
	for (const entry of packageJson.pi.extensions) args.push("-e", resolve(repositoryRoot, entry));
	args.push("--help");

	const result = spawnSync("pi", args, {
		encoding: "utf8",
		timeout: 60_000,
		env: {
			...process.env,
			HOME: home,
			XDG_CONFIG_HOME: join(home, ".config"),
			PI_CODING_AGENT_DIR: join(home, ".pi-agent"),
			MY_PI_SEARCH_CONFIG: join(home, "missing-search.env"),
			PI_OFFLINE: "1",
			TAVILY_API_KEY: "",
			EXA_API_KEY: "",
			KEENABLE_API_KEY: "",
		},
	});

	assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
	assert.doesNotMatch(`${result.stdout}\n${result.stderr}`, /Failed to load extension|conflicts with/u);
});
