import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
import { readFileSync, existsSync } from 'fs';
import { resolve, join } from 'path';
import { fileURLToPath } from 'url';

const __dirname = fileURLToPath(new URL('.', import.meta.url));

// Custom Vite plugin to serve pre-built static apps in dev mode
function serveStaticApps() {
  const staticRoutes = {
    '/guides/statistical-tests': resolve(__dirname, '../../guides/statistical-tests'),
    '/tools/flowchart': resolve(__dirname, '../../tools/flowchart')
  };

  return {
    name: 'serve-static-apps',
    configureServer(server) {
      server.middlewares.use((req, res, next) => {
        const url = req.url?.split('?')[0] || '';

        for (const [route, basePath] of Object.entries(staticRoutes)) {
          if (url.startsWith(route)) {
            let filePath = url.slice(route.length) || '/index.html';
            if (filePath === '/') filePath = '/index.html';

            const fullPath = join(basePath, filePath);
            if (existsSync(fullPath)) {
              try {
                const content = readFileSync(fullPath);
                const ext = filePath.split('.').pop() || 'html';
                const mimeTypes = {
                  'html': 'text/html',
                  'js': 'application/javascript',
                  'css': 'text/css',
                  'json': 'application/json',
                  'png': 'image/png',
                  'jpg': 'image/jpeg',
                  'svg': 'image/svg+xml',
                  'woff': 'font/woff',
                  'woff2': 'font/woff2'
                };
                res.setHeader('Content-Type', mimeTypes[ext] || 'application/octet-stream');
                res.end(content);
                return;
              } catch (e) {
                // Fall through to next handler
              }
            }
          }
        }
        next();
      });
    }
  };
}

export default defineConfig({
  plugins: [serveStaticApps(), sveltekit()]
});
