// composables/useMarkdownStream.js
import { ref, computed, nextTick } from 'vue'
import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js'
// 引入 highlight.js 样式
import 'highlight.js/styles/github.css'
import mdKatex from '@traptitech/markdown-it-katex'

export function useStream() {

  const rawContent = ref('')

  const createMd = () => {
    const md = new MarkdownIt(
      {
        html: true,
        breaks: true,  // 将换行符转换为 <br>
        linkify: true,   // 自动链接 URL
        typographer: true, // 启用排版扩展
        highlight: function (str, lang) {
          if (lang && hljs.getLanguage(lang)) {
            try {
              return '<pre class="hljs" style="fontSize:14px"><code class="language-' + lang + '">' +
                hljs.highlight(str, {
                  language: lang,
                  ignoreIllegals: true
                }).value +
                '</code></pre>'
            } catch (err) {
              console.warn(`代码高亮错误 (${lang}):`, err)
            }
          }

          // 默认处理
          return '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + '</code></pre>'
        }
      }

    )

    // 自定义代码块渲染规则
    md.renderer.rules.fence = (tokens, idx, options, env, self) => {
      const token = tokens[idx]
      const lang = token.info.trim()
      const code = token.content

      // 使用 highlight.js 进行高亮
      if (lang && hljs.getLanguage(lang)) {
        try {
          const highlighted = hljs.highlight(code, {
            language: lang,
            ignoreIllegals: true
          })
          return `
          <div class="code-block-wrapper">
            <div class="code-header">
              <span class="code-lang">${lang}</span>
            </div>
            <pre class="hljs"><code class="language-${lang}">${highlighted.value}</code></pre>
          </div>
        `
        } catch (err) {
          console.warn(`代码高亮错误 (${lang}):`, err)
        }
      }

      // 默认代码块
      return `
      <div class="code-block-wrapper">
        <div class="code-header">
          <span class="code-lang">${lang || 'text'}</span>
          <button class="copy-btn" onclick="copyCode(this)">复制</button>
        </div>
        <pre class="hljs"><code>${md.utils.escapeHtml(code)}</code></pre>
      </div>
    `
    }


    // 自定义表格渲染规则
    md.renderer.rules.table_open = () =>
      '<div class="table-container"><table style="border-collapse: collapse; width: 100%; margin: 1em 0; border: 1px solid #dfe2e5;background: rgb(239 241 243); border-radius: 5px">'

    md.renderer.rules.table_close = () => '</table></div>'

    md.renderer.rules.thead_open = () => '<thead style="background: #e6e7e8">'

    md.renderer.rules.th_open = () =>
      '<th style="border: 1px solid #dfe2e5; padding: 12px; text-align: left; font-weight: 600;">'

    md.renderer.rules.td_open = () =>
      '<td style="border: 1px solid #dfe2e5; padding: 12px; text-align: left; vertical-align: top;">'

    md.renderer.rules.th_close = () => '</th>'
    md.renderer.rules.td_close = () => '</td>'
    md.renderer.rules.tr_open = () => '<tr>'
    md.renderer.rules.tr_close = () => '</tr>'
    md.renderer.rules.thead_close = () => '</thead>'
    md.renderer.rules.tbody_open = () => '<tbody>'
    md.renderer.rules.tbody_close = () => '</tbody>'

    return md
  }


  // 渲染 markdown
  const renderedProcess = computed(() => {

    const md = createMd()
    // 预处理内容
    return md.render(rawContent.value)
  })

  // 自动滚动
  const scrollToBottom = async (scrollContainer) => {
    await nextTick()
    if (scrollContainer) {
      scrollContainer.scrollTop = scrollContainer.scrollHeight
    }
  }

  // 更新内容并滚动
  const updateProcess = async (newContent, scrollContainer) => {
    rawContent.value = newContent
    await scrollToBottom(scrollContainer)
  }

  // 清空内容
  const clearContent = () => {
    rawContent.value = ''
  }

  return {
    rawContent,
    renderedProcess,
    updateProcess,
    clearContent
  }
}