#!/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 ovmArtifactPaths = getContractJsonFiles(
    path.resolve(__dirname, `../artifacts-ovm/contracts`)
  )

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

  ${ovmArtifactPaths
    .map((artifactPath) => {
      const artifact = require(artifactPath)
      const relPath = path.relative(__dirname, artifactPath)
      return `
      let ovm__${artifact.contractName}
      try {
        ovm__${artifact.contractName} = require('${relPath}')
      } catch {}
      `
    })
    .join('\n')}
  ${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, ovm: boolean): any => {
    if (ovm) {
      return {
        ${ovmArtifactPaths
          .map((artifactPath) => {
            const artifact = require(artifactPath)
            return `${artifact.contractName}: ovm__${artifact.contractName}`
          })
          .join(',\n')}
      }[name]
    } else {
      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)
