import esbuild from 'esbuild'
import process from 'process'
import builtins from 'builtin-modules'
import fs from 'fs'
import path from 'path'

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'

const renameCssPlugin = () => ({
	name: 'rename-css',
	setup (build) {
		build.onEnd(() => {
			const outDir = path.dirname(build.initialOptions.outfile || 'main.js')
			const mainCss = path.join(outDir, 'main.css')
			const stylesCss = path.join(outDir, 'styles.css')

			if (fs.existsSync(mainCss)) {
				fs.renameSync(mainCss, stylesCss)
				console.log(`Renamed ${mainCss} to ${stylesCss}`)
			}
		})
	}
})

const context = await esbuild.context({
	banner: {
		js: banner
	},
	entryPoints: ['main.ts'],
	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: 'es2019', // Обновляем таргет до es2019
	logLevel: 'info',
	sourcemap: prod ? false : 'inline',
	treeShaking: true,
	outfile: 'main.js',
	minify: prod,
	// ДОБАВЛЕНО: Загрузчик для CSS файлов
	loader: {
		'.css': 'css'
	},
	plugins: [renameCssPlugin()]
})

if (prod) {
	await context.rebuild()
	process.exit(0)
} else {
	await context.watch()
}
