import { defineConfig } from 'vite';
import { sveltekit } from '@sveltejs/kit/vite';
import tailwindcss from '@tailwindcss/vite';
import { readFileSync } from 'fs';

const pkg = JSON.parse(readFileSync('./package.json', 'utf-8'));

export default defineConfig({
    cacheDir: 'node_modules/.vite',
    define: {
        __BUILD_TIME__: JSON.stringify(new Date().toISOString()),
        __BUILD_VERSION__: JSON.stringify(pkg.version)
    },
    plugins: [
        tailwindcss(),
        sveltekit() // <-- Must come after Tailwind
    ],
    server: {
        watch: {
            // Do not trigger HMR/reload for documentation or test files
            ignored: ['**/documentation/**', '**/tests/**', '**/graphify-out/**']
        }
    },
    optimizeDeps: {
        // @codemirror/* uses dynamic imports that confuse esbuild's pre-bundler; excluded here
        // so vite-plugin-svelte handles them through the normal transform pipeline instead.
        // flowbite-svelte: ONLY exclude if you upgrade to a version that ships TypeScript
        // optional-param syntax (x?, date?) in its compiled dist files — verify with grep
        // before adding it back. Excluding it causes tailwindcss 4.3+ to receive raw .svelte
        // file content (including TypeScript) for style virtual modules, which it rejects.
        exclude: ['@codemirror/*'],
        include: []
    },
    ssr: {
        // Avoid forcing ESM conversion on large editor libs; let them be handled as-is
        noExternal: ['@codemirror/*']
    },
    build: {
        sourcemap: false,
        minify: 'esbuild',
        rollupOptions: {
            output: {
                // Keep all svelte internals in one chunk to prevent circular
                // dependency warnings between runtime.js and index-client.js
                manualChunks(id) {
                    if (id.includes('/node_modules/svelte/')) {
                        return 'svelte-vendor';
                    }
                }
            }
        }
    }
});
