local _, addon = ...

local function FillNumberPositionPlaceholder(text, sourceText)
    if not sourceText or sourceText == "" then return text end

    local numbers = {}
    local source = addon.API.ClearStringFormatMarks(sourceText)

    for num in source:gmatch("(%d[%d,%.]*)") do
        table.insert(numbers, num)
    end

    local replacedText = text:gsub("{nO(%d+)}", function(position)
        position = tonumber(position)
        local n = numbers[position]

        if n then
            if source:match("%s+" .. n .. "%s+million") then
                return n .. " <mil>"
            elseif source:match("%s+" .. n .. "%s+millions") then
                return n .. " <mil>"
            else
                return n
            end
        end

        return "?"
    end)

    return replacedText
end

-- Prepare description for Encounter ability
local function FormatEncounterDescription(text, original)
    local formated = FillNumberPositionPlaceholder(text, original)
    formated = addon.API.ParseParagraphs(original, formated)
    formated = addon.API.ColorSpellNames(formated)

    -- fix [mil], 4 s, 5 %
    formated = string.gsub(formated, "<mil>", "mil.")
    formated = string.gsub(formated, "(%d+) s([%s%.%,%?%!])", "%1s%2")
    formated = string.gsub(formated, "(%d+) %%([%s%.])", "%1%%%2")

    return formated
end
addon.API.FormatEncounterDescription = FormatEncounterDescription

-- Get Encounter object
local function GetEncounter(bossKey)
    local data = addon.data.encounter[bossKey]
    if not data then return nil end

    return {
        abilities = data.abilities or {},
        overview = data.overview.summary or nil,
        tank = data.overview.tank or nil,
        healer = data.overview.healer or nil,
        dps = data.overview.dps or nil,
    }
end
addon.API.GetEncounter = GetEncounter