/**
 * /app 前端热补丁：解析 command-name / local-command-stdout 标签并套用样式。
 * 在 safe-a 重新构建前，由 main.ts 注入到 index.html。
 */
;(function () {
  function escapeHtml(str) {
    return String(str)
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
  }

  function renderSlashCommandMarkup(text) {
    if (
      text.indexOf('<command-name>') === -1 &&
      text.indexOf('<local-command-stdout>') === -1 &&
      text.indexOf('<local-command-stderr>') === -1
    ) {
      return null
    }
    const tagRe =
      /<(command-name|local-command-stdout|local-command-stderr)>([\s\S]*?)<\/\1>/g
    let html = ''
    let last = 0
    let m
    while ((m = tagRe.exec(text))) {
      if (m.index > last) {
        const rest = text.slice(last, m.index).trim()
        if (rest) {
          html +=
            '<span class="chat-slash-xml-rest">' + escapeHtml(rest) + '</span>'
        }
      }
      const tag = m[1]
      const inner = m[2].replace(/^\n+|\n+$/g, '')
      if (tag === 'command-name') {
        html +=
          '<span class="chat-command-name">' + escapeHtml(inner.trim()) + '</span>'
      } else if (tag === 'local-command-stdout') {
        html +=
          '<pre class="chat-local-command-stdout">' + escapeHtml(inner) + '</pre>'
      } else {
        html +=
          '<pre class="chat-local-command-stderr">' + escapeHtml(inner) + '</pre>'
      }
      last = m.index + m[0].length
    }
    if (last < text.length) {
      const tail = text.slice(last).trim()
      if (tail) {
        html += '<span class="chat-slash-xml-rest">' + escapeHtml(tail) + '</span>'
      }
    }
    return html || null
  }

  function patchNode(el) {
    if (!el || el.nodeType !== 1 || el.dataset.slashCmdPatched === '1') return
    const text = el.textContent || ''
    const html = renderSlashCommandMarkup(text)
    if (!html) return
    el.innerHTML = html
    el.dataset.slashCmdPatched = '1'
    el.classList.add('chat-slash-xml-body')
  }

  function scan(root) {
    if (!root || !root.querySelectorAll) return
    root.querySelectorAll('.chat-msg-system-body').forEach(patchNode)
    root.querySelectorAll('.chat-msg-user').forEach(function (userEl) {
      const body =
        userEl.querySelector('.chat-slash-xml-body') ||
        userEl.querySelector('.rounded-md') ||
        userEl.querySelector('.chat-user-body')
      if (body) patchNode(body)
    })
  }

  function boot() {
    scan(document.body)
    var obs = new MutationObserver(function (mutations) {
      for (var i = 0; i < mutations.length; i++) {
        var m = mutations[i]
        if (m.type === 'childList') {
          for (var j = 0; j < m.addedNodes.length; j++) {
            var n = m.addedNodes[j]
            if (n.nodeType === 1) scan(n)
          }
        }
      }
    })
    obs.observe(document.body, { childList: true, subtree: true })
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', boot)
  } else {
    boot()
  }
})()
