import { readFileSync } from "node:fs";
import { join } from "node:path";
import tailwindcss from "@tailwindcss/postcss";
import postcss from "postcss";
import type { Plugin } from "vite";
import { scopeCss } from "./src/wp/scope-css";
import { FALLBACK_SCOPE, KEYFRAME_PREFIX } from "./src/wp/scope";
import {
  FALLBACK_STYLESHEET,
  FONT_FACES,
  FONT_LICENCES,
  FONTS_DIR,
  LOGO_FILE,
} from "./brand-sources";

// What makes a plugin screen look like AccessiBit and is not code: the two
// typefaces, the logo, and the stylesheet of the pages PHP prints on its own
// (a notice instead of the app, the screens with JavaScript off). All of it
// comes from where the dashboard keeps it, so there is one copy of each:
// the fonts and the logo from its `public/`, the colours from
// `src/styles/theme.css`.

/** fontsource's latin range, which these files were cut to. */
const LATIN =
  "U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304," +
  "U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215," +
  "U+FEFF,U+FFFD";

/** `accessibit-fonts.css`: the faces, with addresses relative to the file. */
export function fontFaceCss(): string {
  return FONT_FACES.map(
    ({ family, weight, file }) =>
      `@font-face{font-family:"${family}";font-style:normal;font-weight:${weight};` +
      `font-display:swap;src:url("fonts/${file}") format("woff2");unicode-range:${LATIN}}`,
  ).join("\n");
}

/**
 * `accessibit-fallback.css`: `src/wp/fallback.css` with the theme's tokens,
 * confined to `.accessibit-fallback` the way the app's stylesheet is confined
 * to its root.
 */
export async function fallbackCss(): Promise<string> {
  const result = await postcss([
    tailwindcss({ base: import.meta.dirname }),
    scopeCss(FALLBACK_SCOPE, KEYFRAME_PREFIX),
  ]).process(readFileSync(FALLBACK_STYLESHEET, "utf8"), {
    from: FALLBACK_STYLESHEET,
  });
  return result.css;
}

const BRAND_ID = "virtual:accessibit-admin-brand";

/**
 * Emits the fonts, their stylesheet, the fallback stylesheet and the logo
 * beside the bundle, and gives the bundle the logo as a data URI: wp-admin
 * can then draw it without knowing where the plugin's files are served from.
 */
export function brandAssets(): Plugin {
  return {
    name: "accessibit-admin-brand-assets",
    resolveId: (id) => (id === BRAND_ID ? `\0${BRAND_ID}` : undefined),
    load(id) {
      if (id !== `\0${BRAND_ID}`) return undefined;
      this.addWatchFile(LOGO_FILE);
      const logo = `data:image/svg+xml;base64,${readFileSync(LOGO_FILE).toString("base64")}`;
      return `export default ${JSON.stringify({ logo })};`;
    },
    async generateBundle() {
      for (const { file } of FONT_FACES) {
        this.emitFile({
          type: "asset",
          fileName: `fonts/${file}`,
          source: readFileSync(join(FONTS_DIR, file)),
        });
      }
      this.emitFile({
        type: "asset",
        fileName: "accessibit-fonts.css",
        source: fontFaceCss() + "\n",
      });
      this.emitFile({
        type: "asset",
        fileName: "accessibit-fallback.css",
        source: await fallbackCss(),
      });
      this.emitFile({
        type: "asset",
        fileName: "accessibit-logo.svg",
        source: readFileSync(LOGO_FILE),
      });
    },
  };
}

/** The fonts' licences, in the shape third-party-notices.ts lists. */
export function fontNotices(): { name: string; text: string }[] {
  return FONT_LICENCES.map(({ name, file }) => ({
    name,
    text: `${name} (OFL-1.1), latin subset, in fonts/\n\n${readFileSync(join(FONTS_DIR, file), "utf8").trim()}`,
  }));
}
