local _, addonTable = ...

local KEYSTONE_UPGRADE_TRACK_IRON = "iron"
local KEYSTONE_UPGRADE_TRACK_MYTHIC = "mythic"

addonTable.KEYSTONE_UPGRADE_TRACK_IRON = KEYSTONE_UPGRADE_TRACK_IRON
addonTable.KEYSTONE_UPGRADE_TRACK_MYTHIC = KEYSTONE_UPGRADE_TRACK_MYTHIC

function addonTable.MatchKeystoneUpgradeTrackText(text)
    if type(text) ~= "string" or text == "" then
        return nil
    end

    if text:find("坚韧等级", 1, true) or text:find("堅韌等級", 1, true) then
        return KEYSTONE_UPGRADE_TRACK_IRON
    end

    if text:find("史诗等级", 1, true) or text:find("史詩等級", 1, true) then
        return KEYSTONE_UPGRADE_TRACK_MYTHIC
    end

    return nil
end

function addonTable.ResolveKeystoneUpgradeTrackFromLink(keystoneLink, displayLevel)
    if type(keystoneLink) ~= "string" or keystoneLink == "" then
        return nil
    end

    local linkPayload = keystoneLink:match("|Hkeystone:([^|]+)|h") or keystoneLink:match("keystone:([^|]+)")
    if type(linkPayload) ~= "string" then
        return nil
    end

    local linkFields = {}
    for value in linkPayload:gmatch("([^:]+)") do
        linkFields[#linkFields + 1] = value
    end

    local mythicLevel = tonumber(linkFields[3])
    local fortUpgradeLevel = tonumber(linkFields[#linkFields])
    local normalizedDisplayLevel = tonumber(displayLevel)

    if normalizedDisplayLevel and mythicLevel and normalizedDisplayLevel == mythicLevel then
        if not fortUpgradeLevel or fortUpgradeLevel <= 0 or normalizedDisplayLevel > fortUpgradeLevel then
            return KEYSTONE_UPGRADE_TRACK_MYTHIC
        end

        if normalizedDisplayLevel == fortUpgradeLevel then
            return KEYSTONE_UPGRADE_TRACK_IRON
        end
    end

    if fortUpgradeLevel and fortUpgradeLevel > 0 then
        return KEYSTONE_UPGRADE_TRACK_IRON
    end

    if fortUpgradeLevel == 0 then
        return KEYSTONE_UPGRADE_TRACK_MYTHIC
    end

    return nil
end
