import { defineConfig } from 'vite';
import { svelte } from '@sveltejs/vite-plugin-svelte';
import { sveltePreprocess } from 'svelte-preprocess';

import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import livereload from 'rollup-plugin-livereload';
import terser from '@rollup/plugin-terser';
import babel from '@rollup/plugin-babel'
import typescript from '@rollup/plugin-typescript'

const production = process.env.NODE_ENV === "production"
console.log("Production mode:", production)

const builddir = "../res/static/svelte"
const name = "wrap"

export default defineConfig({
	mode: production ? "production" : "development",
	build: {
		outDir: builddir,
		emptyOutDir: true,
		minify: production,
		sourcemap: !production,
		lib: {
			entry: "src/wrap.js",
			name: "nova_web",
			fileName: name,
		}
	},
	plugins: [
		svelte({
			preprocess: sveltePreprocess(),
			compilerOptions: {},
			emitCss: false,
		}),


		babel({
			extensions: [".js", ".ts", ".svelte"],
			babelHelpers: "bundled",
		}),

		// If you have external dependencies installed from npm, you'll most
		// likely need these plugins. In some cases you'll need additional
		// configuration - consult the documentation for details:
		// https://github.com/rollup/plugins/tree/master/packages/commonjs
		resolve({
			browser: true,
			exportConditions: ['svelte'],
			modulePaths: [process.cwd() + "/src", process.cwd() + "/node_modules"],
			extensions: [".svelte", ".mjs", ".js", ".json", ".mts", ".ts"],
		}),
		commonjs(),
		typescript(),

		// Watch the `public` directory and refresh the browser on changes when
		// not in production
		!production && livereload({
			watch: `${builddir}/${name}.*`,
			port: 5000,
		}),

		// If we're building for production (npm run build instead of npm run
		// dev), minify
		production && terser(),
	]
});
