local _, addon = ...

-- Parse ability information from data
local function ParseAbilities(input, delimiter)
    local result = {}
    local pattern = "([^" .. delimiter .. "]*)"
    local normalizedAbility = string.gsub(input, "||", "|???|")

    local lastPos = 1
    for part in string.gmatch(normalizedAbility, pattern) do
        table.insert(result, part)
        lastPos = lastPos + #part + 1
    end

    if input:sub(-1) == delimiter then
        table.insert(result, "")
    end

    return result
end
addon.API.ParseAbilities = ParseAbilities

-- Replace special marks with actual numbers from original description
local function FillNumberPositionPlaceholder(text, sourceText)
    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("<#(%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

-- Return specific Encounter Ability data
local function GetEncounterAbility(abilityKey)
    return addon.data.encounter[abilityKey].m or nil
end
addon.API.GetEncounterAbility = GetEncounterAbility

-- Get Encounter object
local function GetEncounter(bossKey)
    return {
        abilities = addon.data.encounter[bossKey] or nil,
        overview = addon.data.encounter[bossKey .. "_summary_instance"].m or nil,
        tank = addon.data.encounter[bossKey .. "_summary_tank"].m or nil,
        healer = addon.data.encounter[bossKey .. "_summary_healer"].m or nil,
        dps = addon.data.encounter[bossKey .. "_summary_dps"].m or nil,
    }
end
addon.API.GetEncounter = GetEncounter