/**
 * 聊天场景 Markdown 渲染（AI 回复等），html: false 降低 XSS 风险
 */
import MarkdownIt from "markdown-it"
import hljs from "highlight.js/lib/highlight"
import "highlight.js/styles/github-gist.css"

hljs.registerLanguage("javascript", require("highlight.js/lib/languages/javascript"))
hljs.registerLanguage("json", require("highlight.js/lib/languages/json"))
hljs.registerLanguage("java", require("highlight.js/lib/languages/java"))
hljs.registerLanguage("python", require("highlight.js/lib/languages/python"))
hljs.registerLanguage("xml", require("highlight.js/lib/languages/xml"))
hljs.registerLanguage("bash", require("highlight.js/lib/languages/bash"))
hljs.registerLanguage("sql", require("highlight.js/lib/languages/sql"))

const md = new MarkdownIt({
  html: false,
  linkify: true,
  breaks: true,
  highlight(str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return '<pre class="hljs"><code>' + hljs.highlight(lang, str, true).value + "</code></pre>"
      } catch (e) {
        /* fall through */
      }
    }
    try {
      return '<pre class="hljs"><code>' + hljs.highlightAuto(str).value + "</code></pre>"
    } catch (e2) {
      /* fall through */
    }
    return '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + "</code></pre>"
  }
})

/** 将 Markdown 文本转为可 v-html 使用的 HTML */
export function renderChatMarkdown(text) {
  return md.render(text == null ? "" : String(text))
}
