import { existsSync, readdirSync, readFileSync, realpathSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import type { Plugin } from "vite";

/** What the plugin's GPL-2.0-or-later can carry. */
const GPL_COMPATIBLE = new Set([
  "MIT",
  "ISC",
  "0BSD",
  "BSD-2-Clause",
  "BSD-3-Clause",
  "Apache-2.0",
]);

/**
 * MIT packages whose tarball leaves the licence file out, with the copyright
 * line of the LICENSE in their repository. A new one fails the build until it
 * is added here.
 */
const MIT_WITHOUT_FILE: [RegExp, string][] = [
  [/^@radix-ui\//, "Copyright (c) 2022 WorkOS"],
  [
    /^react-remove-scroll-bar$/,
    "Copyright (c) 2025 Anton Korzunov <thekashey@gmail.com>",
  ],
];

const mit = (copyright: string) => `MIT License

${copyright}

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.`;

/**
 * The root of every package a stylesheet `@import`s, following its relative
 * imports. PostCSS resolves those, so they never reach the module graph.
 */
function stylesheetPackageRoots(
  file: string,
  seen = new Set<string>(),
): string[] {
  if (seen.has(file)) return [];
  seen.add(file);
  const css = readFileSync(file, "utf8");
  return [...css.matchAll(/@import\s+(?:url\()?["']([^"']+)["']/g)].flatMap(
    ([, specifier]) => {
      if (specifier!.startsWith(".")) {
        return stylesheetPackageRoots(resolve(dirname(file), specifier!), seen);
      }
      const name = specifier!
        .split("/")
        .slice(0, specifier!.startsWith("@") ? 2 : 1)
        .join("/");
      return [packageRoot(name, dirname(file))];
    },
  );
}

/** Where Node would find `name` from `dir`, symlinks resolved. */
function packageRoot(name: string, dir: string): string {
  const candidate = join(dir, "node_modules", name);
  if (existsSync(candidate)) return realpathSync(candidate);
  if (dirname(dir) === dir) throw new Error(`Cannot find ${name}`);
  return packageRoot(name, dirname(dir));
}

/**
 * THIRD-PARTY-NOTICES.txt beside the WordPress bundle (ACC-582): the licence,
 * and NOTICE for Apache-2.0, of every package that made it into the bundle,
 * since the minifier keeps only a few of their headers. Fails on a package
 * the GPL cannot carry or whose licence text it cannot find.
 */
export function thirdPartyNotices(
  stylesheet: string,
  /** What ships beside the bundle without being a package: the fonts. */
  extra: { name: string; text: string }[] = [],
): Plugin {
  return {
    name: "accessibit-admin-third-party-notices",
    generateBundle(_, bundle) {
      const roots = new Set(stylesheetPackageRoots(stylesheet));
      for (const chunk of Object.values(bundle)) {
        if (chunk.type !== "chunk") continue;
        for (const [id, mod] of Object.entries(chunk.modules)) {
          const match = /^(.*\/node_modules\/(?:@[^/]+\/)?[^/]+)\//.exec(id);
          // `\0` ids are the CommonJS plugin's proxies of real files.
          if (match && !id.startsWith("\0") && mod.renderedLength > 0) {
            roots.add(match[1]!);
          }
        }
      }

      const notices = [...roots].map((root) => {
        const pkg = JSON.parse(
          readFileSync(join(root, "package.json"), "utf8"),
        ) as { name: string; version: string; license: string };
        const label = `${pkg.name}@${pkg.version}`;
        if (!GPL_COMPATIBLE.has(pkg.license)) {
          this.error(
            `${label} is licensed "${pkg.license}", not one the GPL can carry`,
          );
        }
        const texts = readdirSync(root)
          .filter((file) => /^(licen[cs]e|copying|notice)(\.|$)/i.test(file))
          .sort()
          .map((file) => readFileSync(join(root, file), "utf8").trim());
        if (texts.length === 0) {
          const copyright = MIT_WITHOUT_FILE.find(([name]) =>
            name.test(pkg.name),
          )?.[1];
          if (pkg.license !== "MIT" || !copyright) {
            this.error(
              `${label} ships no licence text: add its copyright to MIT_WITHOUT_FILE`,
            );
          }
          texts.push(mit(copyright));
        }
        return {
          name: pkg.name,
          text: `${label} (${pkg.license})\n\n${texts.join("\n\n")}`,
        };
      });
      // npm, unlike pnpm, can install one version at several paths.
      const unique = [
        ...new Map(
          [...notices, ...extra].map((notice) => [notice.text, notice]),
        ).values(),
      ];

      this.emitFile({
        type: "asset",
        fileName: "THIRD-PARTY-NOTICES.txt",
        source:
          "The AccessiBit admin bundle (accessibit-admin.js, accessibit-admin.css,\n" +
          "accessibit-fallback.css and the fonts beside them) includes the following\n" +
          "third-party software and typefaces.\n\n" +
          unique
            .sort((a, b) => a.name.localeCompare(b.name))
            .map((notice) => notice.text)
            .join(`\n\n${"-".repeat(80)}\n\n`) +
          "\n",
      });
    },
  };
}
