import { fileURLToPath } from "node:url";

const ROOT = new URL("../../../../../", import.meta.url);
const PACKAGES_ROOT = fileURLToPath(new URL("packages/", ROOT));

export function resolve(specifier, context, nextResolve) {
	let tsSpecifier = specifier;
	if (specifier.includes("@singularity-forge/")) {
		tsSpecifier = specifier
			.replace("@singularity-forge/", PACKAGES_ROOT)
			.replace("/dist/", "/src/");
		if (tsSpecifier.includes("/packages/ai") && !tsSpecifier.endsWith(".ts")) {
			tsSpecifier = tsSpecifier.replace(
				/\/packages\/ai$/,
				"/packages/ai/src/index.ts",
			);
		} else if (!tsSpecifier.includes("/src/") && !tsSpecifier.endsWith(".ts")) {
			// Fallback for other sf packages like coding-agent, tui, agent-core
			tsSpecifier = tsSpecifier.replace(
				/\/packages\/([^/]+)$/,
				"/packages/$1/src/index.ts",
			);
		} else if (
			!tsSpecifier.endsWith(".ts") &&
			!tsSpecifier.endsWith(".js") &&
			!tsSpecifier.endsWith(".mjs")
		) {
			tsSpecifier += "/index.ts";
		}
	} else if (specifier.endsWith(".js")) {
		tsSpecifier = specifier.replace(/\.js$/, ".ts");
	}

	return nextResolve(tsSpecifier, context);
}
