import { existsSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";

function firstExisting(paths) {
	return paths.find((candidate) => existsSync(candidate)) ?? null;
}

export function getMarketplaceFixtures(testDir) {
	const home = process.env.HOME ?? "";
	const repoRoot = resolve(
		dirname(fileURLToPath(import.meta.url)),
		"..",
		"..",
		"..",
		"..",
		"..",
	);
	const parent = resolve(testDir, "..", "..", "..");
	const grandparent = resolve(parent, "..");

	const claudeSkillsPath = firstExisting(
		[
			process.env.CLAUDE_SKILLS_MARKETPLACE_PATH,
			join(home, "repos", "claude_skills"),
			join(parent, "claude_skills"),
			join(grandparent, "claude_skills"),
			join(repoRoot, "..", "claude_skills"),
		].filter(Boolean),
	);

	const claudePluginsOfficialPath = firstExisting(
		[
			process.env.CLAUDE_PLUGINS_OFFICIAL_MARKETPLACE_PATH,
			join(home, ".codex", "plugins", "cache", "claude-plugins-official"),
			join(home, ".claude", "plugins", "cache", "claude-plugins-official"),
			join(
				home,
				".claude",
				"plugins",
				"marketplaces",
				"claude-plugins-official",
			),
			join(home, "repos", "claude-plugins-official"),
			join(parent, "claude-plugins-official"),
			join(grandparent, "claude-plugins-official"),
			join(repoRoot, "..", "claude-plugins-official"),
		].filter(Boolean),
	);

	const available = Boolean(claudeSkillsPath && claudePluginsOfficialPath);
	return {
		available,
		skipReason: available ? null : "Claude marketplace fixture repos not found",
		fixtures: available
			? {
					claudeSkillsPath,
					claudePluginsOfficialPath,
				}
			: null,
	};
}
