import esbuild from "esbuild";
import process from "process";
import builtins from "builtin-modules";

const banner =
`/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
`;

const prod = (process.argv[2] === "production");

// CSS bundling function
const buildStyles = async () => {
	await esbuild.build({
		entryPoints: ["styles/index.css"],
		bundle: true,
		outfile: "styles.css",
		minify: prod,
		logLevel: "info",
	});
};

const context = await esbuild.context({
	banner: {
		js: banner,
	},
	entryPoints: ["main.tsx"],
	bundle: true,
	external: [
		"obsidian",
		"electron",
		"@codemirror/autocomplete",
		"@codemirror/collab",
		"@codemirror/commands",
		"@codemirror/language",
		"@codemirror/lint",
		"@codemirror/search",
		"@codemirror/state",
		"@codemirror/view",
		"@lezer/common",
		"@lezer/highlight",
		"@lezer/lr",
		...builtins
	],
	format: "cjs",
	target: "es2018",
	logLevel: "info",
	sourcemap: prod ? false : "inline",
	treeShaking: true,
	outfile: "main.js",
	minify: prod,
	jsx: "transform",
	jsxFactory: "React.createElement",
	jsxFragment: "React.Fragment",
});

// CSS context for watch mode
const cssContext = await esbuild.context({
	entryPoints: ["styles/index.css"],
	bundle: true,
	outfile: "styles.css",
	minify: prod,
	logLevel: "info",
});

if (prod) {
	await context.rebuild();
	await buildStyles(); // Build CSS in production mode
	process.exit(0);
} else {
	await context.watch();
	await cssContext.watch(); // Watch CSS files in development mode
}