export function normalizeMarkdown(value: string) {
  return value.replace(/\r\n/g, '\n')
}

export function countLineDiff(left: string, right: string) {
  const leftLines = normalizeMarkdown(left).split('\n')
  const rightLines = normalizeMarkdown(right).split('\n')
  const previous = new Array(rightLines.length + 1).fill(0)

  for (let leftIndex = 1; leftIndex <= leftLines.length; leftIndex += 1) {
    const current = new Array(rightLines.length + 1).fill(0)

    for (let rightIndex = 1; rightIndex <= rightLines.length; rightIndex += 1) {
      if (leftLines[leftIndex - 1] === rightLines[rightIndex - 1]) {
        current[rightIndex] = previous[rightIndex - 1] + 1
      } else {
        current[rightIndex] = Math.max(previous[rightIndex], current[rightIndex - 1])
      }
    }

    for (let rightIndex = 0; rightIndex <= rightLines.length; rightIndex += 1) {
      previous[rightIndex] = current[rightIndex]
    }
  }

  const common = previous[rightLines.length]

  return {
    additions: Math.max(rightLines.length - common, 0),
    deletions: Math.max(leftLines.length - common, 0),
  }
}
