/**
 * Minimal Node.js import hook for running tests from dist-test/.
 *
 * esbuild with bundle:false preserves import specifiers verbatim, so compiled
 * .js files still import '../foo.ts'. This hook redirects those to '.js' so
 * Node can find the compiled output.
 *
 * Also redirects @sf bare imports to their compiled counterparts in dist-test.
 */

// dist-test root — everything compiled lands here
const DIST_TEST = new URL("../dist-test/", import.meta.url).href;

// Absolute paths to compiled @singularity-forge/* entry points
const SF_ALIASES = {
	"@singularity-forge/pi-coding-agent": new URL(
		"../dist-test/packages/pi-coding-agent/src/index.js",
		import.meta.url,
	).href,
	"@singularity-forge/pi-ai/oauth": new URL(
		"../dist-test/packages/pi-ai/src/utils/oauth/index.js",
		import.meta.url,
	).href,
	"@singularity-forge/pi-ai": new URL(
		"../dist-test/packages/pi-ai/src/index.js",
		import.meta.url,
	).href,
	"@singularity-forge/pi-agent-core": new URL(
		"../dist-test/packages/pi-agent-core/src/index.js",
		import.meta.url,
	).href,
	"@singularity-forge/pi-tui": new URL(
		"../dist-test/packages/pi-tui/src/index.js",
		import.meta.url,
	).href,
	"@singularity-forge/native": new URL(
		"../dist-test/packages/native/src/index.js",
		import.meta.url,
	).href,
};

export function resolve(specifier, context, nextResolve) {
	// 1. @singularity-forge/* bare imports → compiled dist-test counterpart
	if (specifier in SF_ALIASES) {
		return nextResolve(SF_ALIASES[specifier], context);
	}

	// 2. .ts relative imports inside dist-test → .js
	if (
		specifier.endsWith(".ts") &&
		(specifier.startsWith("./") || specifier.startsWith("../")) &&
		context.parentURL &&
		context.parentURL.startsWith(DIST_TEST)
	) {
		const jsSpecifier = specifier.slice(0, -3) + ".js";
		return nextResolve(jsSpecifier, context);
	}

	return nextResolve(specifier, context);
}
