CowmeraRCDB = CowmeraRCDB or {}
CowmeraRCDB.loot = CowmeraRCDB.loot or {}

local function rcprint(msg)
    print("|cff22c55e[CowmeraRC]|r " .. tostring(msg))
end

local function countEntries()
    return #(CowmeraRCDB.loot or {})
end

local function normalizeHistoryEntry(name, history)
    local itemLink = history and history.lootWon or nil
    local itemID = nil
    if type(itemLink) == "string" then
        itemID = tonumber(string.match(itemLink, "item:(%d+)"))
    end

    return {
        player = name or "Unknown",
        item = itemLink,
        itemID = itemID,
        date = history and history.date or "",
        time = history and history.time or "",
        instance = history and history.instance or "",
        boss = history and history.boss or "",
        response = history and history.response or "",
        responseID = history and history.responseID or "",
        votes = history and history.votes or 0,
        id = history and history.id or (tostring(time()) .. ":" .. tostring(itemID or 0) .. ":" .. tostring(name or "Unknown")),
    }
end

local function addEntry(entry)
    if type(entry) ~= "table" then return false end
    CowmeraRCDB.loot = CowmeraRCDB.loot or {}

    local id = tostring(entry.id or "")
    if id ~= "" then
        for _, existing in ipairs(CowmeraRCDB.loot) do
            if tostring(existing.id or "") == id then
                return false
            end
        end
    end

    table.insert(CowmeraRCDB.loot, entry)
    while #CowmeraRCDB.loot > 1000 do
        table.remove(CowmeraRCDB.loot, 1)
    end
    return true
end

local function importExistingHistory()
    local src = _G.RCLootCouncilLootDB
    local fr = src and src.factionrealm
    if type(fr) ~= "table" then
        rcprint("No RCLootCouncil history DB found.")
        return 0
    end

    local added = 0
    for playerName, entries in pairs(fr) do
        if type(entries) == "table" then
            for _, history in ipairs(entries) do
                if addEntry(normalizeHistoryEntry(playerName, history)) then
                    added = added + 1
                end
            end
        end
    end
    return added
end

local function hookRCLootHistory()
    if not _G.RCLootCouncil then
        return false, "RCLootCouncil not loaded."
    end

    local ok, LootHistory = pcall(function()
        return RCLootCouncil:GetModule("RCLootHistory", true)
    end)
    if not ok or not LootHistory then
        return false, "RCLootHistory module not found."
    end

    if LootHistory.__cowmeraRCHooked then
        return true, "Already hooked."
    end
    LootHistory.__cowmeraRCHooked = true

    local orig = LootHistory.OnHistoryReceived
    function LootHistory:OnHistoryReceived(name, history)
        if orig then
            orig(self, name, history)
        end
        addEntry(normalizeHistoryEntry(name, history))
    end

    return true, "Hook active."
end

SLASH_COWMERARC1 = "/cowmerarc"
SLASH_COWMERARC2 = "/crc"
SlashCmdList["COWMERARC"] = function(msg)
    msg = tostring(msg or ""):lower():gsub("^%s+", ""):gsub("%s+$", "")
    if msg == "status" then
        local hooked = false
        if _G.RCLootCouncil then
            local ok, LootHistory = pcall(function()
                return RCLootCouncil:GetModule("RCLootHistory", true)
            end)
            hooked = ok and LootHistory and LootHistory.__cowmeraRCHooked or false
        end
        rcprint("entries: " .. tostring(countEntries()))
        rcprint("hooked: " .. tostring(hooked))
    elseif msg == "import" then
        local added = importExistingHistory()
        rcprint("imported " .. tostring(added) .. " entr" .. (added == 1 and "y" or "ies"))
    else
        rcprint("Commands:")
        rcprint("/cowmerarc status")
        rcprint("/cowmerarc import")
    end
end

local f = CreateFrame("Frame")
f:RegisterEvent("ADDON_LOADED")
f:SetScript("OnEvent", function(_, _, addonName)
    if addonName == "RCLootCouncil" then
        C_Timer.After(1, function()
            local ok, msg = hookRCLootHistory()
            if ok then
                rcprint("bridge active")
            else
                rcprint(msg or "bridge inactive")
            end
        end)
    end
end)
