const fs = require('fs').promises
const { resolve, relative } = require('path')
const { shorthands, describeAll } = require('../lib/npm.js')

const addBetweenTags = (doc, startTag, endTag, body) => {
  const startSplit = doc.split(startTag)
  if (startSplit.length !== 2) {
    throw new Error('Did not find exactly one start tag')
  }

  const endSplit = startSplit[1].split(endTag)
  if (endSplit.length !== 2) {
    throw new Error('Did not find exactly one end tag')
  }

  return [
    startSplit[0],
    startTag,
    '\n<!-- automatically generated, do not edit manually -->\n' +
      '<!-- see lib/utils/config/definitions.js -->\n',
    body,
    '\n\n<!-- automatically generated, do not edit manually -->\n' +
      '<!-- see lib/utils/config/definitions.js -->\n',
    endTag,
    endSplit[1],
  ].join('')
}

const addDescriptions = doc => {
  const startTag = '<!-- AUTOGENERATED CONFIG DESCRIPTIONS START -->'
  const endTag = '<!-- AUTOGENERATED CONFIG DESCRIPTIONS END -->'
  return addBetweenTags(doc, startTag, endTag, describeAll())
}

const addShorthands = doc => {
  const startTag = '<!-- AUTOGENERATED CONFIG SHORTHANDS START -->'
  const endTag = '<!-- AUTOGENERATED CONFIG SHORTHANDS END -->'
  const body = Object.entries(shorthands)
    .sort(([shorta, expansiona], [shortb, expansionb]) => {
      // sort by what they're short FOR
      return expansiona.join(' ').localeCompare(expansionb.join(' '), 'en') ||
        shorta.localeCompare(shortb, 'en')
    })
    .map(([short, expansion]) => {
      const dash = short.length === 1 ? '-' : '--'
      return `* \`${dash}${short}\`: \`${expansion.join(' ')}\``
    }).join('\n')
  return addBetweenTags(doc, startTag, endTag, body)
}

const run = async (dir) => {
  const configDoc = resolve(dir, '../content/using-npm/config.md')
  const doc = await fs.readFile(configDoc, 'utf8')

  await fs.writeFile(configDoc, addDescriptions(addShorthands(doc)))

  return `updated ${relative(process.cwd(), configDoc)}`
}

run(__dirname).then(console.log).catch((err) => {
  process.exitCode = 1
  console.error(err)
})
