import { defineConfig, type Options } from 'tsup';
import babel from 'esbuild-plugin-babel';
import packageJson from './package.json';

const external = [
	...Object.keys(packageJson.dependencies || {}),
	...Object.keys(packageJson.peerDependencies || {}),
];

const isWatch = process.argv.includes('--watch');

// React Compiler — automatic memoization for all components and hooks
// babel-plugin-react-compiler needs TypeScript stripped first, so we use @babel/preset-typescript
const reactCompilerPlugin = babel({
	filter: /\.(ts|tsx)$/,
	config: {
		presets: [
			['@babel/preset-typescript', { isTSX: true, allExtensions: true }],
			['@babel/preset-react', { runtime: 'automatic' }],
		],
		plugins: ['babel-plugin-react-compiler'],
	},
});

const shared: Partial<Options> = {
	format: ['cjs', 'esm'],
	dts: true,
	splitting: false,
	sourcemap: true,
	platform: 'browser',
	external,
	esbuildPlugins: [reactCompilerPlugin],
};

export default defineConfig([
	{
		...shared,
		entry: ['src/index.ts'],
		clean: !isWatch,
	},
	{
		...shared,
		entry: ['src/core/index.ts'],
		clean: false,
		outDir: 'dist/core',
	},
	{
		...shared,
		entry: ['src/db/index.ts'],
		clean: false,
		outDir: 'dist/db',
	},
	{
		...shared,
		entry: ['src/hooks/index.ts'],
		clean: false,
		outDir: 'dist/hooks',
	},
	{
		...shared,
		entry: ['src/utils/index.ts'],
		clean: false,
		outDir: 'dist/utils',
	},
	{
		...shared,
		entry: ['src/commands/index.ts'],
		clean: false,
		outDir: 'dist/commands',
	},
	{
		...shared,
		entry: ['src/nodes/index.ts'],
		clean: false,
		outDir: 'dist/nodes',
	},
	{
		...shared,
		entry: ['src/gestures/index.ts'],
		clean: false,
		outDir: 'dist/gestures',
	},
]);
