import { defineConfig, loadEnv, Plugin } from 'vite';
import react from '@vitejs/plugin-react';
import { createHtmlPlugin } from 'vite-plugin-html';
import * as fs from 'fs';
import * as path from 'path';

// Custom plugin to serve static HTML files from public directory BEFORE SPA fallback
function serveStaticHtml(): Plugin {
  return {
    name: 'serve-static-html',
    enforce: 'pre',
    configureServer(server) {
      // Directly adding middleware runs BEFORE internal Vite middlewares
      server.middlewares.use((req, res, next) => {
        // Check if request is for a static HTML file in public
        const url = req.url?.split('?')[0]; // Remove query string
        if (url && url.endsWith('.html') && url !== '/' && url !== '/index.html') {
          const filePath = path.join(process.cwd(), 'public', url);
          if (fs.existsSync(filePath)) {
            res.setHeader('Content-Type', 'text/html; charset=utf-8');
            res.statusCode = 200;
            res.end(fs.readFileSync(filePath, 'utf-8'));
            return;
          }
        }
        next();
      });
    },
  };
}

export default defineConfig(({ mode }) => {
  // Load env file based on mode
  const env = loadEnv(mode, process.cwd(), '');
  
  return {
    plugins: [
      // Serve static HTML files
      serveStaticHtml(),
      react(),
      createHtmlPlugin({
        // Only process main index.html, not public static files
        pages: [
          {
            entry: 'src/main.tsx',
            filename: 'index.html',
            template: 'index.html',
            injectOptions: {
              data: {
                VITE_APP_NAME: env.VITE_APP_NAME || 'PowerOn',
              },
            },
          },
        ],
      }),
    ],
    envPrefix: 'VITE_',
    css: {
      modules: {
        scopeBehaviour: 'local',  // Default behavior for CSS modules
      },
    },
    // Ensure public files are served correctly as static
    publicDir: 'public',
  };
});
