import { delimiter } from "node:path";

/**
 * bundled-extension-paths.ts — serialize and deserialize bundled extension
 * entry-point paths for the SF_BUNDLED_EXTENSION_PATHS environment variable.
 *
 * Purpose: encode a list of absolute file paths into a single string that can
 * be passed through process.env, then decode it back into an array. This lets
 * loader.ts communicate discovered extension entry points to downstream code
 * without relying on mutable global state or repeated filesystem scans.
 *
 * Consumer: loader.ts (sets SF_BUNDLED_EXTENSION_PATHS after discovery),
 * tests/bundled-extension-paths.test.ts (behaviour contracts).
 */

/**
 * Serialises an array of extension entry-point paths into a delimited string.
 *
 * Purpose: produce a compact, environment-variable-safe representation of the
 * bundled extensions that loader.ts discovered. Using the platform path
 * delimiter by default means the encoded string is also a valid PATH-like value.
 *
 * Consumer: loader.ts (assigns the result to process.env.SF_BUNDLED_EXTENSION_PATHS).
 */
export function serializeBundledExtensionPaths(
	paths: readonly string[],
	pathDelimiter = delimiter,
): string {
	return paths.filter(Boolean).join(pathDelimiter);
}

/**
 * Parses a delimited string of extension entry-point paths back into an array.
 *
 * Purpose: recover the original path list from the SF_BUNDLED_EXTENSION_PATHS
 * environment variable. Trimming and filtering empty segments makes the parser
 * tolerant of trailing delimiters or extra whitespace.
 *
 * Consumer: downstream code that reads process.env.SF_BUNDLED_EXTENSION_PATHS
 * to know which bundled extensions are active (e.g. extension loading logic).
 */
export function parseBundledExtensionPaths(
	value: string | undefined,
	pathDelimiter = delimiter,
): string[] {
	return (value ?? "")
		.split(pathDelimiter)
		.map((segment) => segment.trim())
		.filter(Boolean);
}
