-- ============================================================================
-- Vamoose's Companion - Memory
-- Lifetime counts, milestone detection, boss kill ring buffer, streak milestones
-- ============================================================================

VC = VC or {}
VC.Memory = {}

local BOSS_KILL_MAX = 10

-- ============================================================================
-- MILESTONE DEFINITIONS
-- ============================================================================

local MILESTONES = {
    { key = "boss_1",     counter = "bossKills",           threshold = 1,       eventType = "boss" },
    { key = "boss_10",    counter = "bossKills",           threshold = 10,      eventType = "boss" },
    { key = "boss_50",    counter = "bossKills",           threshold = 50,      eventType = "boss" },
    { key = "boss_100",   counter = "bossKills",           threshold = 100,     eventType = "boss" },
    { key = "death_10",   counter = "deaths",              threshold = 10,      eventType = "death" },
    { key = "death_50",   counter = "deaths",              threshold = 50,      eventType = "death" },
    { key = "quest_100",  counter = "questsCompleted",     threshold = 100,     eventType = "quest" },
    { key = "quest_500",  counter = "questsCompleted",     threshold = 500,     eventType = "quest" },
    { key = "achieve_10", counter = "achievementsEarned",  threshold = 10,      eventType = "achieve" },
    { key = "achieve_50", counter = "achievementsEarned",  threshold = 50,      eventType = "achieve" },
    { key = "gold_100k",  counter = "goldEarned",          threshold = 100000,  eventType = "gold" },
    { key = "gold_1m",    counter = "goldEarned",          threshold = 1000000, eventType = "gold" },
    { key = "mp_10",      counter = "mythicPlusCompleted", threshold = 10,      eventType = "mythicplus" },
    { key = "mp_50",      counter = "mythicPlusCompleted", threshold = 50,      eventType = "mythicplus" },
    { key = "fish_50",    counter = "fishCaught",          threshold = 50,      eventType = "fishing" },
    { key = "craft_50",   counter = "craftingCrits",       threshold = 50,      eventType = "crafting" },
    { key = "session_100", counter = "sessionCount",       threshold = 100,     eventType = "login" },
}

-- Index by eventType for fast lookup during CheckMilestones
local MILESTONES_BY_EVENT = {}
for _, m in ipairs(MILESTONES) do
    if not MILESTONES_BY_EVENT[m.eventType] then
        MILESTONES_BY_EVENT[m.eventType] = {}
    end
    table.insert(MILESTONES_BY_EVENT[m.eventType], m)
end

local STREAK_MILESTONES = { 7, 30, 100 }

-- ============================================================================
-- INITIALIZATION
-- ============================================================================

function VC.Memory:Initialize()
    -- Increment session count on each login
    self:IncrementCount("sessionCount")
end

-- ============================================================================
-- LIFETIME COUNTERS
-- ============================================================================

function VC.Memory:IncrementCount(key, amount)
    VC.Store:Dispatch("INCREMENT_LIFETIME_COUNT", { key = key, amount = amount })
end

function VC.Memory:GetCount(key)
    return VC.Store:GetState().memory.lifetimeCounts[key] or 0
end

-- ============================================================================
-- BOSS KILL RING BUFFER
-- ============================================================================

function VC.Memory:RecordBossKill(entry)
    self:IncrementCount("bossKills")
    VC.Store:Dispatch("PUSH_BOSS_KILL", { entry = entry })
end

-- ============================================================================
-- MILESTONE DETECTION
-- ============================================================================

function VC.Memory:CheckMilestones(eventType)
    local candidates = MILESTONES_BY_EVENT[eventType]
    if not candidates then return end

    local state = VC.Store:GetState()
    local counts = state.memory.lifetimeCounts
    local fired = state.memory.milestonesFired

    for _, m in ipairs(candidates) do
        local count = counts[m.counter] or 0
        if count >= m.threshold and not fired[m.key] then
            VC.Store:Dispatch("SET_MILESTONE_FIRED", { key = m.key })
            self:FireMilestoneQuote(m.key, eventType)
        end
    end
end

function VC.Memory:FireMilestoneQuote(milestoneKey, eventType)
    if not VC.Engine then return end
    local quote = VC.Engine:FindQuoteByTag("milestone", milestoneKey)
    if not quote then
        if VC.Store:GetState().config.debug then
            print("|cFFA0522D[VC Memory]|r No milestone quote for:", milestoneKey)
        end
        return
    end
    VC.Engine:ProcessEvent({
        eventType = "milestone",
        intensity = VC.Constants.INTENSITY.EPIC,
        context = { milestoneKey = milestoneKey, sourceEvent = eventType },
        timestamp = GetTime(),
        source = "VC_MILESTONE",
        milestoneQuoteId = quote.id,
    })
end

-- ============================================================================
-- STREAK MILESTONES
-- ============================================================================

function VC.Memory:CheckStreakMilestones(streakDays)
    local fired = VC.Store:GetState().memory.streakMilestonesFired

    for _, threshold in ipairs(STREAK_MILESTONES) do
        local key = "streak_" .. threshold
        if streakDays >= threshold and not fired[key] then
            VC.Store:Dispatch("SET_STREAK_MILESTONE_FIRED", { key = key })
            self:FireMilestoneQuote(key, "login")
        end
    end
end

-- ============================================================================
-- GETTERS (for /vc status and future UI)
-- ============================================================================

function VC.Memory:GetLifetimeCounts()
    return VC.Store:GetState().memory.lifetimeCounts
end

function VC.Memory:GetRecentBossKills()
    return VC.Store:GetState().memory.bossKills
end
