local WhatLockoutNS = _G.WhatLockout
if not WhatLockoutNS then return end

WhatLockoutNS.CommsHelpers = WhatLockoutNS.CommsHelpers or {}
local CommsHelpers = WhatLockoutNS.CommsHelpers

-- Raids: merge encounter kills, progress "X/Y", and synced bossSummary.
function CommsHelpers.GetRaidBossDisplayCounts(e)
    local ed, et = 0, 0
    if type(e) == "table" and type(e.encounters) == "table" then
        for _, enc in ipairs(e.encounters) do
            if enc and enc.name then
                et = et + 1
                if enc.killed then
                    ed = ed + 1
                end
            end
        end
    end
    local pd, pt = 0, 0
    if type(e) == "table" and type(e.progress) == "string" then
        local p1, p2 = e.progress:match("^(%d+)%s*/%s*(%d+)$")
        if p1 and p2 then
            pt = tonumber(p2) or 0
            pd = tonumber(p1) or 0
        end
    end
    local sd = tonumber(e and e.bossDefeatedCount) or 0
    local st = tonumber(e and e.bossTotalCount) or 0

    if et > 0 then
        local t = (pt > 0) and math.max(pt, et) or et
        local d = math.max(pd, ed, sd)
        return d, t
    end
    if pt > 0 then
        return math.max(pd, sd), pt
    end
    return sd, st
end

function CommsHelpers.RaidDifficultyLetter(diff)
    local s = tostring(diff or ""):lower()
    if s == "" then return nil end
    if s:find("mythic", 1, true) or s:find("mythisch", 1, true) or s:find("mítico", 1, true) then
        return "M"
    end
    if s:find("hero", 1, true) or s:find("heroisch", 1, true) or s:find("héro", 1, true) or s:find("heroico", 1, true) then
        return "H"
    end
    if s:find("lfr", 1, true) or s:find("finder", 1, true) or s:find("sucher", 1, true) or s:find("raid browser", 1, true) then
        return "L"
    end
    if s:find("normal", 1, true) or s:find("normaal", 1, true) then
        return "N"
    end
    return nil
end

function CommsHelpers.ExtractMplusSummaryFromRows(rows)
    if type(rows) ~= "table" then return nil end

    local highestRow = nil
    for _, r in ipairs(rows) do
        if type(r) == "table" and r.isHighest then
            highestRow = r
            break
        end
    end
    if not highestRow then return nil end

    local highestKey = nil
    if type(highestRow.progress) == "string" then
        highestKey = tonumber(highestRow.progress:match("^%+?(%d+)$")) or nil
    end

    local mapsAtMax = highestRow.mapsAtMax
    if type(mapsAtMax) ~= "table" then
        mapsAtMax = {}
    end

    if highestKey and highestKey > 0 then
        return { highestKey = highestKey, mapsAtMax = mapsAtMax }
    end

    return { highestKey = nil, mapsAtMax = mapsAtMax }
end
