const colors = require('picocolors');

/**
 * @param {string} value
 * @returns {string}
 */
function terminalMarkdown(value) {
  return (
    value
      // Handle `---`
      .replace(/^-{3,}$/gm, new Array(process.stdout.columns || 3).fill('-').join(''))
      // Handle headings
      .replace(/^#{1,6} (.*)$/gm, (_, match) =>
        colors.bold(colors.green(`${terminalMarkdown(match)}\n`)),
      )
      // Handle code
      .replace(/`([^`]+)`/g, (_, match) => colors.yellow(terminalMarkdown(match)))
      // Handle bold
      .replace(/\*\*([^*]+)\*\*/g, (_, match) => colors.bold(terminalMarkdown(match)))
      // Handle italic
      .replace(/__([^_]+)__/g, (_, match) => colors.blue(terminalMarkdown(match)))
      // Remove artifacts
      .replace(/\\/g, '')
  );
}

module.exports = terminalMarkdown;
