export const WEB_SEARCH_NODE_TYPE = 'web_search_block'
export const WEB_SEARCH_TRIGGER_TEXT = '[WEBSEARCH]'
export const WEB_SEARCH_RESULT_FENCE_LANG = 'llm-websearch'
export const WEB_SEARCH_CONTEXT_LIMIT = 32 * 1024

const WEB_SEARCH_TRIGGER_RE = /^\[websearch\]$/i
const WEB_SEARCH_RESULT_RE = /(^|\n)(`{3,})llm-websearch(?:\s+date=([^\s`]+))?[^\n]*\n([\s\S]*?)\n\2(?=\n|$)/g

function normalizeMarkdownText(value = '') {
  return String(value || '').replace(/\r\n?/g, '\n')
}

function pickFence(content = '') {
  const matches = String(content || '').match(/`{3,}/g) || []
  const maxLen = matches.reduce((max, item) => Math.max(max, item.length), 2)
  return '`'.repeat(maxLen + 1)
}

function sanitizeDate(value = '') {
  const text = String(value || '').trim()
  if (!text) return ''
  const parsed = new Date(text)
  if (Number.isNaN(parsed.getTime())) return ''
  return parsed.toISOString()
}

function clipText(value = '', limit = 0) {
  if (!limit || value.length <= limit) return value
  return `${value.slice(0, limit)}...`
}

export function parseWebSearchTriggerSyntax(value = '') {
  const text = normalizeMarkdownText(value).trim()
  if (!WEB_SEARCH_TRIGGER_RE.test(text)) return null
  return {
    content: '',
    createdAt: '',
    collapsed: false,
    autoStart: false,
  }
}

export function buildWebSearchResultMarkdown(attrs = {}) {
  const content = normalizeMarkdownText(attrs.content || '').trimEnd()
  const createdAt = sanitizeDate(attrs.createdAt) || new Date().toISOString()
  const fence = pickFence(content)
  return `${fence}${WEB_SEARCH_RESULT_FENCE_LANG} date=${createdAt}\n${content}\n${fence}`
}

export function parseWebSearchResultMarkdown(value = '', meta = '') {
  const content = normalizeMarkdownText(value).replace(/\s+$/, '')
  const dateMatch = String(meta || '').match(/(?:^|\s)date=([^\s`]+)/i)
  return {
    content,
    createdAt: sanitizeDate(dateMatch?.[1] || ''),
    collapsed: false,
    autoStart: false,
  }
}

export function buildWebSearchContextFence(attrs = {}) {
  const content = normalizeMarkdownText(attrs.content || '').trim()
  if (!content) return ''
  const fence = pickFence(content)
  return `${fence}markdown\n${content}\n${fence}`
}

export function extractWebSearchContextFromMarkdown(markdown = '', contentLimit = 0) {
  const normalized = normalizeMarkdownText(markdown)
  const contexts = []

  normalized.replace(WEB_SEARCH_RESULT_RE, (_full, _prefix, _fence, date, content) => {
    const fence = buildWebSearchContextFence({
      content: clipText(normalizeMarkdownText(content || '').trim(), contentLimit),
      createdAt: date || '',
    })
    if (fence) contexts.push(fence)
    return _full
  })

  return contexts.join('\n\n')
}

