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

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

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

  const deploymentNames = fs
    .readdirSync(path.resolve(__dirname, '../deployments'), {
      withFileTypes: true,
    })
    .filter((entry) => {
      return entry.isDirectory()
    })
    .map((entry) => {
      return entry.name
    })

  const artifactNames = []
  for (const deploymentName of deploymentNames) {
    const deploymentArtifacts = glob.sync(
      path.join(
        path.resolve(__dirname, '../deployments'),
        deploymentName,
        '/*.json'
      )
    )

    for (const artifactPath of deploymentArtifacts) {
      const relPath = path.relative(__dirname, artifactPath)
      const contractName = path.basename(artifactPath, '.json')
      const artifactName = `${deploymentName}__${contractName}`.replace(
        /-/g,
        '_'
      )
      artifactNames.push(artifactName)

      content += `const ${artifactName} = require('${relPath}')\n`
    }
  }

  content += `
  export const getDeployedContractArtifact = (name: string, network: string): any => {
    return {
      ${artifactNames
        .map((artifactName) => {
          return `${artifactName}: ${artifactName}`
        })
        .join(',\n')}
    }[(network + '__' + name).replace(/-/g, '_')]
  }
  `

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