-- ============================================================================
-- RuntimeNPCNames: Discovers NPC names at runtime via mouseover/target
-- Persists to SavedVariables so names accumulate across sessions.
-- Merges into MapperBridge nameTable so BossLootTooltip can display them.
-- ============================================================================

local ADDON_NAME, NS = ...
local ETB = NS.ETB

local RuntimeNPC = {}
ETB.RuntimeNPCNames = RuntimeNPC

-- SavedVariable: ETB_RuntimeNPCNames = { [npcID] = "Name", ... }
-- Declared in .toc SavedVariables line

local cache = {}        -- live session cache (merged from SV on init)
local nameTableRef = nil -- reference to MapperBridge's nameTable.npc

-- ============================================================================
-- GUID → npcID extraction (same logic as BossLootTooltip)
-- ============================================================================

local function GetNPCIDFromGUID(guid)
    if not guid then return nil end
    local unitType, _, _, _, _, npcID = strsplit("-", guid)
    if unitType == "Creature" or unitType == "Vehicle" then
        return tonumber(npcID)
    end
    return nil
end

-- ============================================================================
-- Core: resolve and cache an NPC name from a unit token
-- ============================================================================

local function CacheUnitName(unit)
    local guid = UnitGUID(unit)
    local npcID = GetNPCIDFromGUID(guid)
    if not npcID or npcID == 0 then return end

    -- Already known?
    if cache[npcID] then return end

    local name = UnitName(unit)
    if not name or name == "" or name == UNKNOWNOBJECT then return end

    -- Store in live cache
    cache[npcID] = name

    -- Persist to SavedVariables
    if ETB_RuntimeNPCNames then
        ETB_RuntimeNPCNames[npcID] = name
    end

    -- Inject into live nameTable if available
    if nameTableRef and not nameTableRef[npcID] then
        nameTableRef[npcID] = name
    end
end

-- ============================================================================
-- Event handlers
-- ============================================================================

local frame = CreateFrame("Frame")

frame:RegisterEvent("UPDATE_MOUSEOVER_UNIT")
frame:RegisterEvent("PLAYER_TARGET_CHANGED")

frame:SetScript("OnEvent", function(self, event)
    if event == "UPDATE_MOUSEOVER_UNIT" then
        CacheUnitName("mouseover")
    elseif event == "PLAYER_TARGET_CHANGED" then
        CacheUnitName("target")
    end
end)

-- ============================================================================
-- Initialization: load SavedVariables, merge into nameTable
-- Called from Init.lua after PLAYER_LOGIN (C_Timer.After(1, ...))
-- ============================================================================

function RuntimeNPC:Initialize()
    -- Load persisted names from SavedVariables
    ETB_RuntimeNPCNames = ETB_RuntimeNPCNames or {}
    for npcID, name in pairs(ETB_RuntimeNPCNames) do
        cache[npcID] = name
    end

    -- Get reference to MapperBridge's live nameTable
    local SDA = ETB.SourceData_ATT
    if SDA and SDA.GetNPCName then
        -- We'll inject via MergeIntoNameTable instead
    end

    local count = 0
    for _ in pairs(cache) do count = count + 1 end
    if count > 0 then
        ETB:Debug("RuntimeNPC", string.format("Loaded %d cached NPC names from SavedVariables", count))
    end
end

-- ============================================================================
-- Merge all cached names into nameTable.npc (call after MapperBridge init)
-- ============================================================================

function RuntimeNPC:MergeIntoNameTable(npcNameTable)
    if not npcNameTable then return 0 end
    nameTableRef = npcNameTable  -- keep reference for live updates

    local merged = 0
    for npcID, name in pairs(cache) do
        if not npcNameTable[npcID] then
            npcNameTable[npcID] = name
            merged = merged + 1
        end
    end
    return merged
end

-- ============================================================================
-- Public API
-- ============================================================================

function RuntimeNPC:GetName(npcID)
    return cache[npcID]
end

function RuntimeNPC:GetCount()
    local count = 0
    for _ in pairs(cache) do count = count + 1 end
    return count
end

-- Slash command integration: /etb npcnames
function RuntimeNPC:PrintStats()
    local svCount = 0
    if ETB_RuntimeNPCNames then
        for _ in pairs(ETB_RuntimeNPCNames) do svCount = svCount + 1 end
    end
    ETB:Print(string.format("RuntimeNPCNames: %d cached (%d from SavedVariables)", RuntimeNPC:GetCount(), svCount))
end
