import assert from "node:assert/strict";
import { chmod, mkdir, mkdtemp, readFile, writeFile } 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 {
		dependencies: Record<string, string>;
		files: string[];
		pi: { extensions: string[] };
	};
	assert.ok(
		packageJson.pi.extensions.includes("./extensions/plugin-init.ts"),
		"the bundle must expose the project plugin initializer command",
	);
	assert.ok(
		packageJson.pi.extensions.includes("./hippo-memory-pi/index.ts"),
		"the bundle must load the vendored official Hippo Memory extension",
	);
	assert.ok(
		packageJson.pi.extensions.includes("./pi-minimal-footer/index.ts"),
		"the bundle must load the locally maintained minimal footer",
	);
	assert.ok(
		packageJson.pi.extensions.includes("./pi-extension-codex-fast-mode/index.ts"),
		"the bundle must load the locally maintained Codex Fast mode extension",
	);
	assert.ok(packageJson.pi.extensions.includes("./pi-ssh/index.ts"), "the bundle must load the locally maintained SSH extension");
	assert.equal(packageJson.dependencies["pi-ssh"], "file:./pi-ssh");
	assert.equal(packageJson.dependencies.ssh2, "1.17.0", "the packed bundle must install pi-ssh's runtime transport");
	assert.equal(packageJson.dependencies.jiti, "2.7.0", "the packed helper must load local TypeScript outside Pi");
	assert.ok(packageJson.files.includes("pi-ssh"), "the packed bundle must include the locally maintained SSH source");
	assert.ok(packageJson.files.includes("ssh_config.sh"), "the packed bundle must include the SSH host import helper");
	assert.ok(packageJson.pi.extensions.includes("./pi-ask-user/index.ts"), "the bundle must load pi-ask-user");
	assert.equal(packageJson.dependencies["pi-ask-user"], "file:./pi-ask-user");
	assert.ok(packageJson.files.includes("pi-ask-user"), "the packed bundle must include pi-ask-user source");
	const permissionConfig = JSON.parse(
		await readFile(join(repositoryRoot, "config", "pi-permission-system.json"), "utf8"),
	) as { authorizerChain: string[]; permission: Record<string, unknown> };
	assert.equal(permissionConfig.permission.ssh_connect, "ask", "SSH connection must enter the permission gate");
	assert.deepEqual(permissionConfig.authorizerChain, ["auto-review"], "SSH connection asks must reach AutoReview");
	assert.ok(
		packageJson.pi.extensions.indexOf("./extensions/permission-system.ts") <
			packageJson.pi.extensions.indexOf("./pi-ssh/index.ts"),
		"the permission service must load before pi-ssh registers its permission bridge",
	);
	assert.ok(
		packageJson.pi.extensions.indexOf("./pi-ssh/index.ts") <
			packageJson.pi.extensions.indexOf("./pi-tool-search/extensions/index.ts"),
		"pi-ssh tools must register before Tool Search builds its catalog",
	);
	assert.ok(
		packageJson.pi.extensions.indexOf("./pi-ask-user/index.ts") <
			packageJson.pi.extensions.indexOf("./pi-tool-search/extensions/index.ts"),
		"ask_user_question must register before Tool Search builds its catalog",
	);
	assert.equal(
		packageJson.dependencies["@firstpick/pi-extension-codex-fast-mode"],
		"file:./pi-extension-codex-fast-mode",
	);
	assert.ok(
		packageJson.files.includes("pi-extension-codex-fast-mode"),
		"the packed bundle must include the locally maintained Codex Fast mode source",
	);
	assert.equal(packageJson.dependencies["@ogulcancelik/pi-minimal-footer"], "file:./pi-minimal-footer");
	assert.equal(
		packageJson.pi.extensions.some((entry) => entry.includes("pi-hermes-memory") || entry.includes("the-forge-flow")),
		false,
		"retired Hermes and third-party Hippo extensions must not be loaded",
	);
	assert.equal(packageJson.dependencies["@the-forge-flow/hippo-memory-pi"], undefined);
	assert.equal(packageJson.dependencies["@sinclair/typebox"], undefined);
	const home = await mkdtemp(join(tmpdir(), "my-pi-extension-load-"));
	const mockBin = join(home, "bin");
	await mkdir(mockBin, { recursive: true });
	const hippo = join(mockBin, "hippo");
	await writeFile(hippo, "#!/bin/sh\nprintf '%s\\n' 'Hippo Memory status'\n", "utf8");
	await chmod(hippo, 0o755);
	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"),
			PATH: `${mockBin}:${process.env.PATH ?? ""}`,
			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);
});
