#!/usr/bin/env -S node -r esbin
import fs from "fs"
import { resolve } from "path"
import { mapValues } from "lodash"
import polyfill from "../api-metadata.json" assert { type: "json" }

function convert(value: any): any {
  return mapValues(value, value => {
    if (typeof value === "object" && value != null) {
      const keyCount = Object.keys(value).length
      if (
        value.minArgs != null &&
        value.maxArgs != null &&
        (keyCount === 2 || (keyCount === 3 && value.fallbackToNoCallback != null))
      ) {
        return [
          value.minArgs,
          value.maxArgs,
          value.fallbackToNoCallback || undefined,
        ].filter(x => x !== undefined)
      } else {
        return convert(value)
      }
    }

    return value
  })
}

fs.writeFileSync(
  resolve(__dirname, "../api-metadata.generated.json"),
  JSON.stringify(convert(polyfill)),
)
