import { defineConfig, type Plugin } from "vite";
import { readFileSync } from "node:fs";

export default defineConfig(({ mode }) => ({
  plugins: [manifestPlugin(mode)],
  build: {
    outDir: `dist/${mode}`,
    // Background scripts and content scripts are classic scripts in Manifest V2.
    // They are rebuilt individually below as self-contained IIFEs, after the
    // regular ESM build has produced the worker and HTML-page bundles.
    emptyOutDir: !process.env.VIBEGUARD_CLASSIC_ENTRY,
    rollupOptions: {
      input: inputsFor(mode),
      output: {
        entryFileNames: "[name].js",
        chunkFileNames: "chunks/[name]-[hash].js",
        assetFileNames: "assets/[name]-[hash][extname]",
        format: process.env.VIBEGUARD_CLASSIC_ENTRY ? "iife" : "es",
        inlineDynamicImports: Boolean(process.env.VIBEGUARD_CLASSIC_ENTRY)
      }
    }
  },
  test: {
    environment: "jsdom",
    globals: true,
    include: ["tests/**/*.test.ts"]
  }
}));

function inputsFor(mode: string): Record<string, string> {
  const classicEntry = process.env.VIBEGUARD_CLASSIC_ENTRY;
  if (classicEntry === "content") return { content: "src/content/main.ts" };
  if (classicEntry === "background") {
    return { background: mode === "firefox" ? "src/background/firefox.ts" : "src/background/chromium.ts" };
  }

  return {
    content: "src/content/main.ts",
    background: mode === "firefox" ? "src/background/firefox.ts" : "src/background/chromium.ts",
    inference: "src/inference/worker.ts",
    options: "src/options/main.ts",
    popup: "src/popup/main.ts",
    offscreen: "src/background/offscreen.ts"
  };
}

function manifestPlugin(mode: string): Plugin {
  return {
    name: "vibeguard-manifest",
    generateBundle() {
      const filename = mode === "firefox" ? "public/manifest.firefox.json" : "public/manifest.chromium.json";
      this.emitFile({ type: "asset", fileName: "manifest.json", source: readFileSync(filename, "utf8") });
      this.emitFile({ type: "asset", fileName: "ort/ort-wasm-simd-threaded.jsep.wasm", source: readFileSync("node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm") });
    }
  };
}
