#!/usr/bin/env -S node -r esbin
import fs from "fs"
import { resolve } from "path"
import * as esbuild from "esbuild"
import { file } from "./utils"
import { getDefaultTarget } from "./plugins/esbuild-browserslist"

const outdir = resolve(__dirname, "../dist/vendor/sass")
fs.rmSync(outdir, { recursive: true, force: true })

const prefix = `
  let window = globalThis;

  let process = {
    env: {},
    stdout: {
      write: console.log
    },
    stderr: {
      write: console.error,
    },
  };
`

const sass = fs.readFileSync(
  resolve(__dirname, "../node_modules", "sass/sass.dart.js"),
  "utf-8",
)

const replaced: string = sass
  .replaceAll(/typeof Buffer/g, '"undefined"')
  .replaceAll("process.stdout.isTTY", "undefined")
  .replaceAll("self.location", "window.location")
  .replace(/require\("(chokidar|readline|fs|util)"\)/g, "{}")
  .replace(
    /(accept|accept\$1|add|call|toString|parse|write|scope\$1|parse[A-Z]\w+)\$(\d): function\(/g,
    "$1$$$2(",
  )
  .replace(/\w+\.util\.inspect\.custom/g, "Symbol()")
  .replace(/(\$eq|toString|get\$\w+|join\$0): function\(/g, "$1(")
  .replace("if (dartNodeIsActuallyNode) {", "if (false) {")
  // CSP
  .replaceAll(
    /new\s+self\.Function\(\s*("[^"\\]*(?:\\.[^"\\]*)*")\s*,\s*("[^"\\]*(?:\\.[^"\\]*)*")\s*\)/g,
    (_, $1, $2) => `((${JSON.parse($1)}) => { ${JSON.parse($2)} })`,
  )
  .replaceAll(
    /new\s+self\.Function\(\s*("[^"\\]*(?:\\.[^"\\]*)*")\s*,\s*('[^'\\]*(?:\\.[^'\\]*)*')\s*\)/g,
    (_, $1, $2) =>
      `((${JSON.parse($1)}) => { ${JSON.parse(
        '"' + $2.slice(1, -1).replaceAll('"', '\\"') + '"',
      )} })`,
  )
  .trim()

const temporary = file.js(prefix + replaced)

const entry = file.js(/* js */ `
  import "${temporary.path}";
  const sass = globalThis._cliPkgExports.pop();
  sass.load({});

  export default sass;
`)

try {
  esbuild.buildSync({
    entryPoints: [entry.path],
    outfile: resolve(outdir, "index.js"),
    bundle: true,
    minify: true,
    format: "esm",
    sourcemap: "external",
    target: getDefaultTarget(),
    external: ["fs", "chokidar", "readline"],
    banner: { js: "/* eslint-disable */" },
    legalComments: "linked",
    define: {
      "process.env.NODE_ENV": '"production"',
      "process.env.NODE_DEBUG": "undefined",
    },
  })
} finally {
  temporary.rm()
  entry.rm()
}
