import { BROCHURE_AUTO_KEYWORDS_SORTED } from '../data/brochureKeywords'

/**
 * 将宣传册正文拆成片段，供 BrochureRichText 渲染为 router-link / 外链。
 *
 * 显式语法（优先级高于自动关键词）：
 *   [[br:topic|显示文字]]      → /brochure/:topic
 *   [[home:锚点|显示文字]]     → 首页 hash，锚点可带或不带 #
 *   [[out:https://...|文字]]   → 新窗口（仅 http/https）
 */
const EXPLICIT_RE =
  /\[\[(br):([\w-]+)\|([^\]]+?)\]\]|\[\[(home):#?([\w-]+)\|([^\]]+?)\]\]|\[\[(out):(https?:[^|\]]+)\|([^\]]+?)\]\]/g

function mergeAdjacentText(arr) {
  const merged = []
  for (const x of arr) {
    if (
      x.type === 'text' &&
      merged.length &&
      merged[merged.length - 1].type === 'text'
    ) {
      merged[merged.length - 1].text += x.text
    } else {
      merged.push({ ...x })
    }
  }
  return merged
}

function segmentAutoKeywords(text, linkBudget) {
  const parts = []
  let pos = 0
  let used = 0
  let plainBuf = ''

  function flushPlain() {
    if (plainBuf) {
      parts.push({ type: 'text', text: plainBuf })
      plainBuf = ''
    }
  }

  while (pos < text.length) {
    if (used >= linkBudget) {
      plainBuf += text.slice(pos)
      break
    }
    let best = null
    for (const { kw, topic } of BROCHURE_AUTO_KEYWORDS_SORTED) {
      if (text.startsWith(kw, pos) && (!best || kw.length > best.kw.length)) {
        best = { kw, topic }
      }
    }
    if (best) {
      flushPlain()
      parts.push({
        type: 'link',
        text: best.kw,
        to: { name: 'Brochure', params: { topic: best.topic } }
      })
      used++
      pos += best.kw.length
    } else {
      plainBuf += text[pos]
      pos++
    }
  }
  flushPlain()
  return parts
}

export function parseBrochureRichText(raw, options = {}) {
  const { autoKeyword = true, maxAutoLinks = 14 } = options
  const str = raw == null ? '' : String(raw)
  if (!str) return [{ type: 'text', text: '' }]

  const chunks = []
  let last = 0
  let m
  EXPLICIT_RE.lastIndex = 0
  while ((m = EXPLICIT_RE.exec(str)) !== null) {
    if (m.index > last) {
      chunks.push({ plain: str.slice(last, m.index) })
    }
    if (m[1] === 'br') {
      chunks.push({ br: true, topic: m[2], label: m[3] })
    } else if (m[4] === 'home') {
      chunks.push({ home: true, hash: m[5], label: m[6] })
    } else if (m[7] === 'out') {
      chunks.push({ out: true, url: m[8], label: m[9] })
    }
    last = EXPLICIT_RE.lastIndex
  }
  if (last < str.length) {
    chunks.push({ plain: str.slice(last) })
  }

  const out = []
  let autoCount = 0

  for (const seg of chunks) {
    if (seg.br) {
      out.push({
        type: 'link',
        text: seg.label,
        to: { name: 'Brochure', params: { topic: seg.topic } }
      })
      continue
    }
    if (seg.home) {
      const h = seg.hash.startsWith('#') ? seg.hash : `#${seg.hash}`
      out.push({
        type: 'link',
        text: seg.label,
        to: { path: '/', hash: h }
      })
      continue
    }
    if (seg.out) {
      if (/^https?:\/\//i.test(seg.url)) {
        out.push({ type: 'link', text: seg.label, external: seg.url })
      } else {
        out.push({ type: 'text', text: `[[out:${seg.url}|${seg.label}]]` })
      }
      continue
    }
    if (seg.plain != null) {
      if (autoKeyword && autoCount < maxAutoLinks) {
        const sub = segmentAutoKeywords(seg.plain, maxAutoLinks - autoCount)
        for (const p of sub) {
          if (p.type === 'link') autoCount++
          out.push(p)
        }
      } else {
        if (seg.plain !== '') out.push({ type: 'text', text: seg.plain })
      }
    }
  }

  return mergeAdjacentText(out)
}
