import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { Language, Parser } from "web-tree-sitter";
//#region src/lib/utilities/tree-sitter-wasm.ts
/**
* Shared WASM loader for web-tree-sitter.
* Provides singleton initialization and cached language loading.
*/
let initialized = false;
/** Resolve a grammar WASM file path relative to the dist/ directory. */
function resolveGrammar(filename) {
	const thisDirectory = dirname(fileURLToPath(import.meta.url));
	return resolve(thisDirectory.includes("/dist/") ? thisDirectory.slice(0, thisDirectory.indexOf("/dist/") + 5) : resolve(thisDirectory, "..", ".."), "grammars", filename);
}
/** Initialize web-tree-sitter (idempotent) and return a new Parser instance. */
async function initParser() {
	if (!initialized) {
		await Parser.init();
		initialized = true;
	}
	return new Parser();
}
let pythonLanguage;
/** Get the Python language (cached after first load). */
async function getPythonLanguage() {
	pythonLanguage ??= await Language.load(resolveGrammar("tree-sitter-python.wasm"));
	return pythonLanguage;
}
let rubyLanguage;
/** Get the Ruby language (cached after first load). */
async function getRubyLanguage() {
	rubyLanguage ??= await Language.load(resolveGrammar("tree-sitter-ruby.wasm"));
	return rubyLanguage;
}
//#endregion
export { getPythonLanguage, getRubyLanguage, initParser };
