local _, addon = ...

-- Split original text by break-lines
local function SplitParagraphs(text)
    local paragraphs = {}
    for paragraph in string.gmatch(text, "([^\n]+)") do
        table.insert(paragraphs, paragraph)
    end
    return paragraphs
end

-- Split text into sentences
local function SplitSentences(paragraph)
    local sentences = {}
    for sentence in string.gmatch(paragraph, "([^%.%?!]+[%.%?!]?)[%s]*") do
        local trimmed = sentence:gsub("^%s+", ""):gsub("%s+$", "")
        if #trimmed > 0 then
            table.insert(sentences, trimmed)
        end
    end
    return sentences
end

-- Put break-lines
local function ReplaceMultipleBreakLines(text)
    return text:gsub("\r?\n+", "\n\n")
end

-- Because decimal numbers contain dot, remove space between those numbers
local function FixDecimalNumbers(text)
    return text:gsub("(%d+)%.%s+(%d+)", "%1.%2")
end

-- Fix translated text break-line based on original
local function ParseParagraphs(original_text, translation_text)
    if original_text == "" or original_text == nil then
        return translation_text
    end

    translation_text = string.gsub(translation_text, "(%d+)%.", function(numberPart)
        local numberWithDot = numberPart .. "."
        if string.find(original_text, numberWithDot, 1, true) then
            return numberWithDot
        else
            return numberPart
        end
    end)

    local original_paragraphs = SplitParagraphs(original_text)
    local translation_paragraphs = {}
    local translation_sentences = SplitSentences(translation_text)
    local counter = 1

    for _, orig_paragraph in ipairs(original_paragraphs) do
        local orig_sentences = SplitSentences(orig_paragraph)
        local paragraph_sentence_count = #orig_sentences
        local collected = {}

        for i = 1, paragraph_sentence_count do
            if translation_sentences[counter] then
                table.insert(collected, translation_sentences[counter])
                counter = counter + 1
            else
                break
            end
        end
        table.insert(translation_paragraphs, table.concat(collected, " "))
    end

    local multilines = ReplaceMultipleBreakLines(table.concat(translation_paragraphs, "\n"))
    local fixedDecimalNumbers = FixDecimalNumbers(multilines)

    return fixedDecimalNumbers
end
addon.API.ParseParagraphs = ParseParagraphs