import { defineConfig } from "vite";
import { VitePWA } from "vite-plugin-pwa";
import vue from "@vitejs/plugin-vue";
import dotenv from "dotenv";
import { loadAppConfig } from "./vite.config.utils";
import path from "path";
import { fileURLToPath } from 'url';

// Load environment variables from .env file
dotenv.config();

// Get dirname in ESM context
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// Load application configuration
const appConfig = loadAppConfig();

export default defineConfig(({ mode }) => {
  const isElectron = mode === "electron";
  const isCapacitor = mode === "capacitor";
  const isPyWebView = mode === "pywebview";

  // Disable PWA features for desktop builds
  if (isElectron || isPyWebView) {
    process.env.VITE_PWA_ENABLED = 'false';
  }

  return {
    base: isElectron || isPyWebView ? "./" : "/",
    server: {
      port: process.env.VITE_PORT || 8080,
      fs: {
        strict: false
      },
    },
    build: {
      outDir: isElectron ? "dist-electron" : "dist",
      assetsDir: 'assets',
      rollupOptions: {
        external: ['electron', 'path'],
        input: {
          main: path.resolve(__dirname, 'index.html')
        },
        output: {
          manualChunks(id) {
            if (isElectron && (
              id.includes('registerServiceWorker') ||
              id.includes('register-service-worker') ||
              id.includes('workbox') ||
              id.includes('sw_scripts') ||
              id.includes('PushNotificationPermission')
            )) {
              return null; // Exclude these modules completely
            }
          }
        }
      },
      chunkSizeWarningLimit: 1000
    },
    define: {
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
      'process.env.VITE_PWA_ENABLED': JSON.stringify(!(isElectron || isPyWebView)),
      __dirname: isElectron ? JSON.stringify(process.cwd()) : '""',
    },
    plugins: [
      vue(),
      {
        name: 'remove-sw-imports',
        transform(code, id) {
          if (isElectron) {
            if (
              id.includes('registerServiceWorker') ||
              id.includes('register-service-worker') ||
              id.includes('sw_scripts') ||
              id.includes('PushNotificationPermission') ||
              code.includes('navigator.serviceWorker')
            ) {
              return {
                code: code
                  .replace(/import.*registerServiceWorker.*$/mg, '')
                  .replace(/import.*register-service-worker.*$/mg, '')
                  .replace(/navigator\.serviceWorker/g, 'undefined')
                  .replace(/if\s*\([^)]*serviceWorker[^)]*\)\s*{[^}]*}/g, '')
              };
            }
          }
        }
      },
      ...(!isElectron && !isCapacitor ? [
        VitePWA({
          disable: true,
          registerType: 'autoUpdate',
          injectRegister: null,
          workbox: {
            cleanupOutdatedCaches: true,
            skipWaiting: true,
            clientsClaim: true,
            sourcemap: true
          },
          manifest: appConfig.pwaConfig?.manifest,
          devOptions: {
            enabled: false
          }
        }),
      ] : []),
    ],
    resolve: {
      alias: appConfig.aliasConfig
    },
    optimizeDeps: {
      exclude: isElectron ? [
        'register-service-worker',
        'workbox-window',
        'web-push',
        'serviceworker-webpack-plugin'
      ] : []
    }
  };
});