-- =========================================================================
-- FILE: WCL_Bridge.lua
-- =========================================================================
-- Provider Interception Bridge for ArchonTooltip (WarcraftLogs)
-- Wraps ArchonTooltip.AddProviderV2/AddProvider to capture the data store.
-- Exposes NS.WCL.GetParses(name, realm) for AXIOM consumption.
-- =========================================================================
local addonName, NS = ...

NS.WCL = {}
NS.WCL.IsAvailable = false

-- Storage: captured provider data tables (keyed by provider key)
local capturedProviders = {}

-- =========================================================================
-- WCL Difficulty ID Mapping
-- =========================================================================
-- WarcraftLogs uses these difficultyId values in ProviderProfileV2Section:
--   3 = Normal
--   4 = Heroic
--   5 = Mythic
local DIFFICULTY_NORMAL  = 3
local DIFFICULTY_HEROIC  = 4
local DIFFICULTY_MYTHIC  = 5

-- =========================================================================
-- WCL Percentile Color Codes (matching ArchonTooltip's Utils.lua palette)
-- =========================================================================
local function GetPercentileColor(pct)
    if not pct or pct <= 0 then return "|cff9d9d9d" end -- Grey (Common)
    if pct < 25  then return "|cff9d9d9d" end           -- Grey
    if pct < 50  then return "|cff1eff00" end           -- Green (Uncommon)
    if pct < 75  then return "|cff0070dd" end           -- Blue (Rare)
    if pct < 95  then return "|cffa335ee" end           -- Purple (Epic)
    if pct < 99  then return "|cffff8000" end           -- Orange (Legendary)
    if pct < 100 then return "|cffe268a8" end           -- Pink (Astounding)
    return "|cffe5cc80"                                  -- Gold (Artifact / 100)
end

NS.WCL.GetPercentileColor = GetPercentileColor

-- =========================================================================
-- PROVIDER INTERCEPTION: Hook ArchonTooltip.AddProvider / AddProviderV2
-- =========================================================================
-- We wrap the global functions BEFORE the DB addons load their data.
-- When ArchonTooltipDB_EU (or other region) calls AddProvider/AddProviderV2,
-- our wrapper captures the provider's data metatable for later querying.

local function InstallHooks()
    if not _G.ArchonTooltip then return false end

    -- Hook AddProvider (V1)
    if _G.ArchonTooltip.AddProvider then
        local originalAddProvider = _G.ArchonTooltip.AddProvider
        _G.ArchonTooltip.AddProvider = function(lookup, provider)
            -- Call original first (installs the metatable on provider.data)
            originalAddProvider(lookup, provider)
            -- Capture the provider's data table for our queries
            if provider and provider.data then
                local key = (provider.realm or "unknown") .. "-" .. (provider.name or "unknown")
                capturedProviders[key] = provider
            end
        end
    end

    -- Hook AddProviderV2 (if it exists — newer versions)
    if _G.ArchonTooltip.AddProviderV2 then
        local originalAddProviderV2 = _G.ArchonTooltip.AddProviderV2
        _G.ArchonTooltip.AddProviderV2 = function(lookup, provider)
            originalAddProviderV2(lookup, provider)
            if provider and provider.data then
                local key = (provider.realm or "unknown") .. "-" .. (provider.name or "unknown")
                capturedProviders[key] = provider
            end
        end
    end

    NS.WCL.IsAvailable = true
    return true
end

-- =========================================================================
-- DATA RETRIEVAL: Query captured providers for a player's profile
-- =========================================================================

--- Retrieve the raw ProviderProfileV2 for a given character.
--- @param name string Character name (no realm)
--- @param realm string Realm name (normalized)
--- @return table|nil profile The ProviderProfileV2 struct, or nil
function NS.WCL.GetProfile(name, realm)
    if not NS.WCL.IsAvailable then return nil end
    if not name or name == "" then return nil end

    -- Iterate over all captured providers and check for the player
    for _, provider in pairs(capturedProviders) do
        if provider.data then
            local profile = provider.data[name]
            if profile then
                return profile
            end
        end
    end
    return nil
end

--- Retrieve parse averages per difficulty for a character.
--- Returns a table { normal=<int>, heroic=<int>, mythic=<int> } or nil.
--- Only returns data the player has NOT hidden (respects isHidden).
--- @param name string Character name (no realm)
--- @param realm string Realm name (normalized)
--- @return table|nil parses
function NS.WCL.GetParses(name, realm)
    local profile = NS.WCL.GetProfile(name, realm)
    if not profile then return nil end

    -- If progressOnly, no detailed sections are available
    if profile.progressOnly then return nil end
    if not profile.sections or #profile.sections == 0 then return nil end

    local result = {}

    for _, section in ipairs(profile.sections) do
        local avg = nil
        if section.anySpecRankings and section.anySpecRankings.bestAverage then
            avg = section.anySpecRankings.bestAverage
            if avg > 0 then
                avg = math.floor(avg + 0.5) -- Round to integer
            else
                avg = nil -- 0 means no data
            end
        end

        if avg then
            if section.difficultyId == DIFFICULTY_NORMAL then
                result.normal = avg
            elseif section.difficultyId == DIFFICULTY_HEROIC then
                result.heroic = avg
            elseif section.difficultyId == DIFFICULTY_MYTHIC then
                result.mythic = avg
            end
        end
    end

    -- Return nil if we found nothing useful
    if not result.normal and not result.heroic and not result.mythic then
        return nil
    end

    return result
end

-- =========================================================================
-- INITIALIZATION: Install hooks as early as possible
-- =========================================================================
-- We try immediately (in case ArchonTooltip loaded before us),
-- then register for ADDON_LOADED to catch it loading after us.

if not InstallHooks() then
    local hookFrame = CreateFrame("Frame")
    hookFrame:RegisterEvent("ADDON_LOADED")
    hookFrame:SetScript("OnEvent", function(self, event, loadedAddon)
        if loadedAddon == "ArchonTooltip" then
            InstallHooks()
        end
    end)
end
