import MarkdownIt from 'markdown-it'

interface MarkdownFactoryOptions {
  referenceLinks?: boolean
}

const REFERENCE_LINK_PATTERN = /\[(\d+)\]/g

const BASE_MARKDOWN_OPTIONS = {
  html: false,
  linkify: true,
  typographer: true,
  breaks: true,
}

export function createMarkdownIt(options: MarkdownFactoryOptions = {}): MarkdownIt {
  const markdown = new MarkdownIt(BASE_MARKDOWN_OPTIONS)

  if (options.referenceLinks) {
    const defaultTextRule = markdown.renderer.rules.text
    markdown.renderer.rules.text = (tokens, idx, renderOptions, env, self) => {
      const rendered = defaultTextRule
        ? defaultTextRule(tokens, idx, renderOptions, env, self)
        : markdown.utils.escapeHtml(tokens[idx].content)
      return rendered.replace(
        REFERENCE_LINK_PATTERN,
        '<a class="ref-link" href="#ref-$1" title="查看引用文档 $1">[$1]</a>',
      )
    }
  }

  return markdown
}