local _, addon = ...

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

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

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

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

    return ReplaceMultipleBreakLines(
            table.concat(translation_paragraphs, "\n")
    )
end
addon.API.ParseParagraphs = ParseParagraphs