#!/usr/bin/env node
/* eslint-disable spaced-comment */
// @ts-check
const fs = require("fs")
const { resolve } = require("path")
const pkg = require("../package.json")

/**
 * @param {TemplateStringsArray} args
 */
function _([source]) {
  return {
    "index.js": `module.exports = ${source};\n`,
    "index.mjs": `export default ${source};\n`,
    "package.json": JSON.stringify({ module: "index.mjs", version: "1.0.0" }),
  }
}

const { entries, fromEntries } = Object

/**
 * @param {Record<string, Record<string, string>>} list
 */
function createShims(list) {
  /** @type {Record<string, string>} */
  const resolutions = fromEntries(
    entries(pkg.resolutions).filter(([, path]) => !path.startsWith("./shims")),
  )

  for (const [name, content] of entries(list)) {
    const dir = resolve(__dirname, "../shims", name)
    fs.mkdirSync(dir, { recursive: true })
    content["package.json"] ??= "{}"

    for (let [fileName, text] of entries(content)) {
      if (fileName === "package.json") {
        text = JSON.stringify({ name, ...JSON.parse(text) })
      }
      fs.writeFileSync(resolve(dir, fileName), text)
    }

    resolutions[name] = `./shims/${name}`
  }

  pkg.resolutions =
    /** @type {any} */
    (fromEntries(entries(resolutions).sort(([a], [b]) => a.localeCompare(b))))

  fs.writeFileSync(resolve(__dirname, "../package.json"), JSON.stringify(pkg, null, 2))
}

createShims({
  "cross-fetch": {
    "index.js": /*js*/ `module.exports = fetch; const headers = Headers; module.exports.Headers = headers;`,
    "index.mjs": /*js*/ `export default fetch; const headers = Headers; export { headers as Headers };`,
    "package.json": JSON.stringify({ module: "index.mjs", version: "1.0.0" }),
  },
  "is-number": _/*js*/ `value => typeof value === "number"`,
})
