-- HDG_HT_DailyXPTracker.lua  (D2 support)
-- Maintains HDG_DB.records.dailyXP[YYYY-MM-DD] = sum of XP deltas for that day.
-- Subscribes to HOUSE_LEVEL_FAVOR_UPDATED, computes delta vs last-seen value,
-- buckets to today's date. Only tracks the active character's house (the API
-- only fires for matching faction). Stale entries beyond 365 days are pruned.

local _, privateDB = ...
privateDB.HDG_HT = privateDB.HDG_HT or {}
local DXP = {}
privateDB.HDG_HT.DailyXPTracker = DXP

local DAY = 86400
local PRUNE_AFTER_DAYS = 365

local _lastByGUID = {}        -- [houseGUID] = lastSeenFavorValue (in-memory)
local _frame = nil

local function getDB()
    HDG_DB = HDG_DB or {}
    HDG_DB.records = HDG_DB.records or {}
    HDG_DB.records.dailyXP = HDG_DB.records.dailyXP or {}
    return HDG_DB.records.dailyXP
end

local function todayKey() return date("%Y-%m-%d", time()) end

local function pruneOld(log)
    local cutoff = time() - PRUNE_AFTER_DAYS * DAY
    for d in pairs(log) do
        local y, m, dy = d:match("(%d+)-(%d+)-(%d+)")
        local yn, mn, dyn = tonumber(y or ""), tonumber(m or ""), tonumber(dy or "")
        if yn and mn and dyn then
            local t = time({ year = yn, month = mn, day = dyn })
            if t < cutoff then log[d] = nil end
        end
    end
end

local function onFavorUpdated(payload)
    if type(payload) ~= "table" then return end
    local guid = payload.houseGUID
    local cur  = payload.houseFavor or payload.currentFavor
    if not guid or type(cur) ~= "number" then return end

    local prev = _lastByGUID[guid]
    _lastByGUID[guid] = cur

    if prev and cur > prev then
        local delta = cur - prev
        local log = getDB()
        local k = todayKey()
        log[k] = (log[k] or 0) + delta
    end
end

function DXP.Init()
    if _frame then return end
    _frame = CreateFrame("Frame")
    _frame:RegisterEvent("HOUSE_LEVEL_FAVOR_UPDATED")
    _frame:RegisterEvent("PLAYER_LOGIN")
    _frame:SetScript("OnEvent", function(_, event, ...)
        if event == "PLAYER_LOGIN" then
            pruneOld(getDB())
        elseif event == "HOUSE_LEVEL_FAVOR_UPDATED" then
            onFavorUpdated(...)
        end
    end)
end

-- Auto-init at file load (TOC ordering: this runs before login firing).
DXP.Init()

return DXP
