-- ══════════════════════════════════════════════════════════════
-- MODUL: Nemesis - Erzfeind der Gilde (Guild Nemesis & Revenge)
-- Die Kreatur, die die meisten Gildenmitglieder getoetet hat, wird
-- zum "Erzfeind". Schlaegt sie erneut zu -> Mahnung. Toetest DU sie
-- -> Rache (lokal gefeiert + optional einmalig an die Gilde).
-- Nutzt die bereits gesyncten Todesdaten -> KEIN neuer State-Sync.
-- ══════════════════════════════════════════════════════════════

local addonName, addon = ...
local GDL = _G["GuildDeathLog"]
local Nemesis = {}

local function T(de, en) return (GDL.WantEnglish and GDL:WantEnglish()) and en or de end

local PREFIX        = "GDLNem"     -- nur fuer den optionalen Rache-Announce
local MIN_KILLS     = 3            -- ab so vielen Opfern gilt jemand als Erzfeind
local REVENGE_COOLDOWN = 60        -- s, Anti-Spam fuer Gilden-Announce
local ICON          = "Interface\\Icons\\Ability_Warrior_Revenge"

Nemesis._cached         = nil      -- {name=, count=} gecacht (kein DB-Scan pro Kill)
Nemesis._lastAnnounce   = 0

-- ── Erzfeind frisch aus den (gesyncten) Todesdaten berechnen ──────────────────
function Nemesis:Compute()
    local Stats = GDL:GetModule("Statistics")
    if not (Stats and Stats.GetDeathsByKiller) then self._cached = nil; return nil end
    local ok, killers = pcall(function() return Stats:GetDeathsByKiller() end)
    local top = ok and killers and killers[1] or nil
    if top and (top.count or 0) >= MIN_KILLS then
        self._cached = { name = top.name, count = top.count }
    else
        self._cached = nil
    end
    return self._cached
end

function Nemesis:Get()
    return self._cached
end

-- ── /gdl nemesis ──────────────────────────────────────────────────────────────
function Nemesis:Print()
    local n = self:Compute()
    if not n then
        GDL:Print(T("Noch kein Erzfeind - die Gilde hat (zum Glueck) zu wenige Verluste.",
                    "No nemesis yet - the guild has (thankfully) too few losses."))
        return
    end
    GDL:Print("|cffFF3333" .. T("Erzfeind der Gilde: ", "Guild Nemesis: ") .. "|r|cffFFD100"
        .. tostring(n.name) .. "|r — "
        .. string.format(T("%d Gildenmitglieder gefallen", "%d guildmates fallen"), n.count))
    local victims = self:GetVictims(n.name, 5)
    if #victims > 0 then
        GDL:Print("|cff888888" .. T("Opfer: ", "Victims: ") .. table.concat(victims, ", ") .. "|r")
    end
end

function Nemesis:GetVictims(killerName, limit)
    local out = {}
    local gd = GDL.GetGuildData and GDL:GetGuildData()
    if not (gd and gd.deaths) then return out end
    for _, d in ipairs(gd.deaths) do
        local k = d.killerName or d.killer
        if k and k == killerName then
            out[#out + 1] = (d.name or "?") .. (d.level and (" (" .. d.level .. ")") or "")
            if #out >= (limit or 5) then break end
        end
    end
    return out
end

-- ── Tod-Hook (von DNLBridge:_PipelineStep2) ───────────────────────────────────
function Nemesis:OnDeath(deathData)
    if not deathData then return end
    self:Compute()                 -- neuer Tod kann den Erzfeind aendern
    local n = self._cached
    if not n then return end
    local killer = deathData.killerName or deathData.killer
    if killer and killer == n.name then
        local msg = string.format(
            T("Der Erzfeind |cffFFD100%s|r hat erneut zugeschlagen — nun %d Gefallene.",
              "The nemesis |cffFFD100%s|r has struck again — now %d fallen."),
            killer, n.count)
        local UI = GDL:GetModule("UI")
        if UI and UI.ShowMilestoneToast then
            UI:ShowMilestoneToast({
                name = T("Erzfeind der Gilde", "Guild Nemesis"),
                desc = msg, icon = ICON, category = "warning",
            })
        end
        GDL:Print("|cffFF3333" .. msg .. "|r")
    end
end

-- ── Combat-Log: erkennt eigene Kills (PARTY_KILL) -> Rache ────────────────────
function Nemesis:OnCombatLog()
    local n = self._cached
    if not n then return end       -- ohne Erzfeind kein DB-/String-Aufwand
    local _, subevent, _, sGUID, _, _, _, _, dName = CombatLogGetCurrentEventInfo()
    if subevent ~= "PARTY_KILL" then return end
    if not dName or dName ~= n.name then return end
    -- Nur eigene Kills (ich oder mein Pet)
    local mine = (sGUID == UnitGUID("player"))
    if not mine then
        local petGUID = UnitGUID("pet")
        mine = petGUID and (sGUID == petGUID)
    end
    if not mine then return end
    self:CelebrateRevenge(n)
end

function Nemesis:CelebrateRevenge(n)
    local msg = string.format(
        T("RACHE! Du hast den Erzfeind der Gilde |cffFFD100%s|r erschlagen.",
          "REVENGE! You slew the guild nemesis |cffFFD100%s|r."), n.name)
    local UI = GDL:GetModule("UI")
    if UI and UI.ShowMilestoneToast then
        UI:ShowMilestoneToast({
            name = T("Rache vollbracht", "Revenge Taken"),
            desc = msg, icon = ICON, category = "success",
        })
    end
    GDL:Print("|cff33FF66" .. msg .. "|r")
    -- Optional einmalig (Anti-Spam) an die Gilde verkuenden
    local now = GetTime()
    if (now - self._lastAnnounce) > REVENGE_COOLDOWN
       and IsInGuild() and C_ChatInfo and C_ChatInfo.SendAddonMessage then
        self._lastAnnounce = now
        local me  = UnitName("player") or "?"
        local mob = (n.name or "?"):gsub("|", "/"):sub(1, 40)
        pcall(C_ChatInfo.SendAddonMessage, PREFIX, "AVENGE|" .. me .. "|" .. mob, "GUILD")
        if GDL.Debug then GDL:Debug("Nemesis: -> SENT AVENGE " .. mob) end
    end
end

function Nemesis:HandleAddonMessage(msg, sender)
    if not msg then return end
    local short = (strsplit("-", sender))
    if short == (UnitName("player")) then return end       -- eigenes Echo
    local cmd, who, mob = strsplit("|", msg)
    if cmd ~= "AVENGE" or not who then return end
    GDL:Print("|cff33FF66" .. string.format(
        T("|cffFFD100%s|r hat Rache am Erzfeind |cffFFD100%s|r genommen!",
          "|cffFFD100%s|r took revenge on the nemesis |cffFFD100%s|r!"),
        who, mob or "?") .. "|r")
    if GDL.Debug then GDL:Debug("Nemesis: <- RECV AVENGE from " .. short) end
end

function Nemesis:Initialize()
    if self._initialized then return end
    self._initialized = true

    if C_ChatInfo and C_ChatInfo.RegisterAddonMessagePrefix then
        pcall(C_ChatInfo.RegisterAddonMessagePrefix, PREFIX)
    end

    local f = CreateFrame("Frame")
    f:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
    f:RegisterEvent("CHAT_MSG_ADDON")
    f:SetScript("OnEvent", function(_, event, ...)
        if event == "COMBAT_LOG_EVENT_UNFILTERED" then
            self:OnCombatLog()
        elseif event == "CHAT_MSG_ADDON" then
            local prefix, message, channel, sender = ...
            if prefix == PREFIX and channel == "GUILD" then
                self:HandleAddonMessage(message, sender)
            end
        end
    end)

    -- Erstberechnung + periodisches Refresh des Erzfeinds (kein Per-Kill-Scan)
    C_Timer.After(8, function() self:Compute() end)
    C_Timer.NewTicker(300, function() self:Compute() end)

    if GDL.Debug then GDL:Debug("Nemesis: initialisiert") end
end

GDL:RegisterModule("Nemesis", Nemesis)
