text: const { Buffer } = require('buffer')
  const { readFile, writeFile } = require('fs')
  const { env } = require('process')
  const { promisify } = require('util')
  
  const glob = require('glob')
  const hastscript = require('hastscript')
  const parseGitHub = require('parse-github-repo-url')
  const parse = require('rehype-parse')
  const stringify = require('rehype-stringify')
  const unified = require('unified')
  const visit = require('unist-util-visit')
  
  const pReadFile = promisify(readFile)
  const pWriteFile = promisify(writeFile)
  const pGlob = promisify(glob)
  
  const addScriptNode = ({ hash }) => (tree) => {
    visit(tree, 'element', (node) => {
      if (node.tagName === 'body') {
        // eslint-disable-next-line fp/no-mutating-methods
        node.children.push(hastscript('script', `window.___NETLIFY_DPC___="${hash}"`))
        // eslint-disable-next-line fp/no-mutating-methods
        node.children.push(hastscript('script', { src: 'https://dpcbp.netlify.app/netlify-dpc.js' }))
      }
    })
  }
  
  const computeDpcHash = () => {
    const ghInfo = parseGitHub(env.REPOSITORY_URL || DEFAULT_REPOSITORY_URL)
    if (!ghInfo) {
      return
    }
  
    const [owner, repo] = ghInfo
  
    const info = {
      netlify_prime_url: env.DEPLOY_PRIME_URL || DEFAULT_DEPLOY_PRIME_URL,
      pull_request_id: env.REVIEW_ID || DEFAULT_REVIEW_ID,
      owner,
      repo,
    }
  
    return Buffer.from(JSON.stringify(info)).toString('base64')
  }
  
  // adding env var fallbacks allows us to build locally with the Netlify CLI
  const DEFAULT_REPOSITORY_URL = 'https://github.com/netlify/netlify-plugin-deploy-preview-commenting'
  const DEFAULT_DEPLOY_PRIME_URL = 'https://deploy-preview-2--dpcbp.netlify.app'
  const DEFAULT_REVIEW_ID = 2
  
  const injectScriptWithHash = async (hash, filePath) => {
    try {
      const contents = await pReadFile(filePath, 'utf-8')
  
      const file = await unified().use(parse).use(addScriptNode, { hash }).use(stringify).process(contents)
      const markup = file.toString()
  
      await pWriteFile(filePath, markup)
  
      return { filePath }
    } catch (error) {
      return { filePath, error }
    }
  }
  
  const injectScript = async function ({ dpcHash, PUBLISH_DIR }) {
    // add the DPC script to all HTML files
    const files = await pGlob(`${PUBLISH_DIR}/**/*.html`)
  
    if (files.length === 0) {
      return { successes: [], failures: [] }
    }
  
    const results = await Promise.all(files.map((file) => injectScriptWithHash(dpcHash, file)))
    const successes = results.filter(({ error }) => error === undefined)
    const failures = results.filter(({ error }) => error !== undefined)
    return { successes, failures }
  }
  
  module.exports = {
    computeDpcHash,
    injectScript,
  }
  