#!/usr/bin/env node
const path = require('path')
const glob = require('glob')
const fs = require('fs')

;(async () => {
  console.log(`writing contract artifacts typescript file`)

  const getContractJsonFiles = (artifactsFolder) => {
    return glob.sync(`${artifactsFolder}/**/*.json`).filter((match) => {
      return !match.endsWith('.dbg.json')
    })
  }

  const evmArtifactPaths = getContractJsonFiles(
    path.resolve(__dirname, `../artifacts/contracts`)
  )

  const content = `
  /* eslint-disable @typescript-eslint/no-var-requires, no-empty */
  /*
  THIS FILE IS AUTOMATICALLY GENERATED.
  DO NOT EDIT.
  */

  ${evmArtifactPaths
    .map((artifactPath) => {
      const artifact = require(artifactPath)
      const relPath = path.relative(__dirname, artifactPath)
      return `
      let ${artifact.contractName}
      try {
        ${artifact.contractName} = require('${relPath}')
      } catch {}
      `
    })
    .join('\n')}

  export const getContractArtifact = (name: string): any => {
    return {
      ${evmArtifactPaths
        .map((artifactPath) => {
          const artifact = require(artifactPath)
          return `${artifact.contractName}: ${artifact.contractName}`
        })
        .join(',\n')}
    }[name]
  }
  `

  fs.writeFileSync(`./src/contract-artifacts.ts`, content)
})().catch(console.error)
