const fs = require("fs");
const path = require("path");
const { defineConfig } = require("vite");
const { viteSingleFile } = require("vite-plugin-singlefile");

const platformBuilds = {
  applovin: { adapter: "applovin", output: "applovin" },
  unity: { adapter: "unity", output: "unity" },
  playturbo: { adapter: "playturbo", output: "playturbo" },
  mintegral: { adapter: "playturbo", output: "mintegral" },
  google: { adapter: "google", output: "google" },
};

function patchSingleFileHtml(htmlPath, adapter) {
  if (!fs.existsSync(htmlPath)) return;
  let html = fs
    .readFileSync(htmlPath, "utf8")
    .replace(/<script\s+type="module"\s+crossorigin>/g, "<script>")
    .replace(/<script\s+crossorigin\s+type="module">/g, "<script>")
    .replace(/<script\s+type="module">/g, "<script>")
    .replace(/<script\s+crossorigin>/g, "<script>")
    .replace(/<style\s+rel="stylesheet"\s+crossorigin>/g, "<style>")
    .replace(/<style\s+crossorigin\s+rel="stylesheet">/g, "<style>")
    .replace(/<style\s+crossorigin>/g, "<style>");

  fs.writeFileSync(htmlPath, html);
}

function finalizeHtmlPlugin(outDir, adapter) {
  return {
    name: "finalize-html-output",
    closeBundle() {
      const htmlPath = path.resolve(__dirname, outDir, "index.html");
      patchSingleFileHtml(htmlPath, adapter);
    },
  };
}

module.exports = defineConfig(({ mode }) => {
  const platformBuild = platformBuilds[mode];
  const adapter = platformBuild?.adapter || "google";
  const output = platformBuild?.output;
  const outDir = output ? `dist/${output}` : "dist";

  return {
    plugins: [viteSingleFile(), finalizeHtmlPlugin(outDir, adapter)],
    server: {
      allowedHosts: ["color2.jccytech.cn", "localhost", ".jccytech.cn"],
    },
    resolve: {
      alias: {
        "#ad-config": path.resolve(
          __dirname,
          process.env.AD_CONFIG_PATH || "src/filler/ad-config.ts",
        ),
        "./ad-platform/current": path.resolve(
          __dirname,
          `src/filler/ad-platform/adapters/${adapter}.ts`,
        ),
      },
    },
    build: {
      // 所有资源内联到 HTML，目标单文件广告
      assetsInlineLimit: 100 * 1024 * 1024, // 不限大小，全部内联
      target: "es2017",
      outDir,
      emptyOutDir: true,
      rollupOptions: {
        input: {
          main: "./index.html",
        },
        output: {
          entryFileNames: "assets/[name].js",
          chunkFileNames: "assets/[name].js",
          assetFileNames: "assets/[name][extname]",
        },
      },
    },
  };
});
