const { definitions } = require('../lib/utils/config/index.js')
const { writeFileSync, readFileSync } = require('fs')
const { resolve } = require('path')

const configDoc = process.argv[2]
const commandFile = process.argv[3]

// Note: commands without params skip this whole process.
const { params } = require(resolve(commandFile))

const describeAll = () =>
  params.map(name => definitions[name].describe()).join(
    '\n\n<!-- automatically generated, do not edit manually -->\n' +
      '<!-- see lib/utils/config/definitions.js -->\n\n'
  )

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\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())
}

// always write SOMETHING so that Make sees the file is up to date.
const doc = readFileSync(configDoc, 'utf8')
const hasTag = doc.includes('<!-- AUTOGENERATED CONFIG DESCRIPTIONS START -->')
const newDoc = params && hasTag ? addDescriptions(doc) : doc
if (params && !hasTag)
  console.error('WARNING: did not find config description section', configDoc)
writeFileSync(configDoc, newDoc)
