import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import tailwindcss from "@tailwindcss/postcss";
import react from "@vitejs/plugin-react";
import { defineConfig, type Plugin } from "vite";
import { pickSiteAdminMessages } from "./src/messages";
import { scopeCss } from "./src/wp/scope-css";
import { KEYFRAME_PREFIX, ROOT_ID } from "./src/wp/scope";
import { brandAssets, fontNotices } from "./brand-assets";
import { thirdPartyNotices } from "./third-party-notices";

// The WordPress plugin's admin bundle (ACC-403): one IIFE plus one scoped
// stylesheet, copied into the plugin zip by its build (ACC-404) and enqueued
// only on the plugin's own admin pages. React 19 is bundled, never borrowed
// from `wp.element`. Shipped under the GPL, so nothing here may pull in the
// statement templates, legal copy, scoring or analytics: the lint in
// AccessiBit's repository fails if src/ tries (eslint.boundary.config.mjs).

const DICTIONARIES = resolve(
  __dirname,
  "../../apps/dashboard/src/app/dictionaries",
);
const MESSAGES_ID = "virtual:accessibit-admin-messages";

/**
 * The dashboard dictionaries, reduced to the slices these components read.
 * Picked here rather than imported whole, which would ship every dashboard
 * string (~220 KB per language) inside the plugin.
 */
function messages(): Plugin {
  return {
    name: "accessibit-admin-messages",
    resolveId: (id) => (id === MESSAGES_ID ? `\0${MESSAGES_ID}` : undefined),
    load(id) {
      if (id !== `\0${MESSAGES_ID}`) return undefined;
      const picked = Object.fromEntries(
        ["en", "it", "es"].map((lang) => {
          const file = resolve(DICTIONARIES, `${lang}.json`);
          this.addWatchFile(file);
          const dict = JSON.parse(readFileSync(file, "utf8"));
          return [lang, pickSiteAdminMessages(dict)];
        }),
      );
      return `export default ${JSON.stringify(picked)};`;
    },
  };
}

/**
 * Fails the build unless the bundle is one IIFE and nothing else: anything
 * beside it is a global on every admin page that loads it. esbuild once
 * hoisted its class-field helpers above the wrapper (ACC-582).
 */
function iifeOnly(): Plugin {
  return {
    name: "accessibit-admin-iife-only",
    generateBundle(_, bundle) {
      for (const chunk of Object.values(bundle)) {
        if (chunk.type !== "chunk") continue;
        const { body } = this.parse(chunk.code);
        const [only] = body;
        const iife =
          body.length === 1 &&
          only?.type === "ExpressionStatement" &&
          only.expression.type === "CallExpression" &&
          /^(Arrow)?FunctionExpression$/.test(only.expression.callee.type);
        if (!iife) {
          this.error(
            `${chunk.fileName} has top-level code beside its IIFE, which would land on window`,
          );
        }
      }
    },
  };
}

export default defineConfig({
  plugins: [
    react(),
    messages(),
    iifeOnly(),
    brandAssets(),
    thirdPartyNotices(resolve(__dirname, "src/wp/styles.css"), fontNotices()),
  ],
  // From source, not the package's build: the plugin ships this source, and
  // there the barrel names only the modules used (written by export-source.ts
  // in AccessiBit's repository).
  resolve: {
    alias: {
      "@accessibit/types": resolve(__dirname, "../types/src/index.ts"),
    },
  },
  // Library mode leaves `process.env.NODE_ENV` for the consumer to replace;
  // there is no consumer here, and React would ship its development build.
  define: { "process.env.NODE_ENV": JSON.stringify("production") },
  css: {
    postcss: {
      plugins: [
        tailwindcss({ base: __dirname }),
        scopeCss(`#${ROOT_ID}`, KEYFRAME_PREFIX),
      ],
    },
  },
  build: {
    outDir: "dist/wp",
    emptyOutDir: true,
    // Class fields are native from es2022; below it esbuild hoists helpers
    // outside the IIFE, onto `window` (see iifeOnly).
    target: "es2022",
    sourcemap: false,
    lib: {
      entry: resolve(__dirname, "src/wp/index.tsx"),
      name: "accessibitAdmin",
      formats: ["iife"],
      fileName: () => "accessibit-admin.js",
    },
    rollupOptions: {
      output: { assetFileNames: "accessibit-admin[extname]" },
    },
  },
});
