import { normalizeNewlines } from './string.js'

const OUTER_FENCE_RE = /^(`{3,}|~{3,})[^\n]*\n([\s\S]*?)\n\1[ \t]*$/

function unescapeLiteralNewlines(value = '') {
  const text = String(value || '')
  if (text.includes('\n') || !/\\n/.test(text)) return text
  return text.replace(/\\n/g, '\n')
}

export function normalizeProAcceptMarkdown(value = '') {
  let text = normalizeNewlines(value)
  const trimmed = text.trim()

  if (!trimmed) return ''

  if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
    try {
      const parsed = JSON.parse(trimmed)
      if (typeof parsed === 'string') {
        text = normalizeNewlines(parsed)
      }
    } catch {
      // Keep the original response when it is not a JSON string literal.
    }
  }

  text = unescapeLiteralNewlines(text)

  const fenceMatch = text.trim().match(OUTER_FENCE_RE)
  if (fenceMatch) {
    return normalizeNewlines(fenceMatch[2]).trim()
  }

  return text.trim()
}

export function splitPlainTextFallbackBlocks(value = '') {
  const text = normalizeNewlines(value).trim()
  if (!text) return []
  return text.split(/\n{2,}/).map((block) => block.trim()).filter(Boolean)
}
