-- WarBoard_Alerts.lua
-- The Alerts intel feed: a live, lightly-throttled log of war events.
--
-- Two shapes of alert:
--   * Assault alerts — a recurring situation ("X under attack") keyed by
--     objective + shard, so the SAME objective on different shards is tracked
--     separately. Continued combat refreshes its timestamp; it ages ACTIVE -> RECENT
--     and finally prunes. Chat warnings are throttled to one per 10 min per key.
--   * Event alerts — point-in-time notices (objective completed, bounty posted,
--     campaign reset, ...) keyed by a unique id so they never duplicate.
--
-- The local player raises assault alerts from their OWN objective-NPC kills and
-- broadcasts them so the defending faction is warned (cross-faction via the realm
-- channel). Completion/bounty/system alerts are raised locally on each client from
-- data it already has, so they need no separate broadcast.

local addonName, WB = ...

WB.Alerts = WB.Alerts or {}
local A = WB.Alerts

-- Categories (drive the feed's colour + tag).
A.CATEGORY = {
    WAR_EFFORT = "war_effort",
    BOUNTY     = "bounty",
    WORLD      = "world",
    SYSTEM     = "system",
}

-- ── Tunables ─────────────────────────────────────────────────────────────────────
local ACTIVE_WINDOW  = 180     -- <= 3 min since last activity  => ACTIVE, else RECENT
local ALERT_TTL      = 1800    -- alerts drop off after 30 min idle
local CHAT_THROTTLE  = 600     -- 10 min between chat warnings per assault key
local BCAST_THROTTLE = 60      -- 1 min between assault re-broadcasts per key
local MAX_ALERTS     = 120

-- ── State ────────────────────────────────────────────────────────────────────────
local db                 -- WarBoardCharDB.alerts  ([id] = alert)
local lastBcastAt = {}   -- assaultKey -> GetTime()  (session only; throttles comm)

local function EnsureDB()
    WarBoardCharDB = WarBoardCharDB or {}
    WarBoardCharDB.alerts     = WarBoardCharDB.alerts     or {}   -- [id] = alert record
    WarBoardCharDB.alertChat  = WarBoardCharDB.alertChat  or {}   -- [key] = time() of last chat warning
    db = WarBoardCharDB
end
local function Ready() if not db then EnsureDB() end return db ~= nil end

local function MyFaction() return WB.faction or UnitFactionGroup("player") or "Horde" end
local function EnemyOf(faction) return (faction == "Alliance") and "Horde" or "Alliance" end
local function CurrentShard()
    return WB.ShardDetector and WB.ShardDetector.GetShardID and WB.ShardDetector:GetShardID() or nil
end

local function RefreshUI()
    if WB.UI and WB.UI.RefreshAlerts then WB.UI.RefreshAlerts() end
end

-- Remove alerts past their TTL; cap the total (drop the stalest).
local function Prune()
    if not db then return end
    local now, n = time(), 0
    for id, al in pairs(db.alerts) do
        if (now - (al.lastSeen or 0)) > ALERT_TTL then db.alerts[id] = nil else n = n + 1 end
    end
    while n > MAX_ALERTS do
        local oldestId, oldestT
        for id, al in pairs(db.alerts) do
            if not oldestT or (al.lastSeen or 0) < oldestT then oldestId, oldestT = id, (al.lastSeen or 0) end
        end
        if not oldestId then break end
        db.alerts[oldestId] = nil
        n = n - 1
    end
    -- Once a key's chat throttle has fully elapsed it can't gate anything; drop it.
    for key, ts in pairs(db.alertChat) do
        if (now - ts) > CHAT_THROTTLE then db.alertChat[key] = nil end
    end
end

-- ── Raising alerts ────────────────────────────────────────────────────────────────

-- Assault: combat against an objective's NPCs. opts:
--   objId, place, zone, attacker, attackerFaction, defenderFaction, shardId
-- `fromRemote` = received over comm (don't re-broadcast).
function A.RecordAssault(opts, fromRemote)
    if not Ready() or type(opts) ~= "table" or not opts.objId then return end
    local shard = opts.shardId
    local key   = "assault:" .. tostring(opts.objId) .. ":" .. tostring(shard or "0")
    local now   = time()

    -- The originating client is the ATTACKER. It spreads the alert to the network so
    -- the DEFENDING faction is warned (throttled per key), but never logs/shows it
    -- locally — an assault is intel for the side being attacked, not the aggressor.
    if not fromRemote then
        local g = GetTime()
        if not lastBcastAt[key] or (g - lastBcastAt[key]) >= BCAST_THROTTLE then
            lastBcastAt[key] = g
            if WB.Comm and WB.Comm.BroadcastAlert then
                WB.Comm.BroadcastAlert({
                    kind = "assault", objId = opts.objId, shardId = shard,
                    place = opts.place, zone = opts.zone, attacker = opts.attacker,
                    attackerFaction = opts.attackerFaction, defenderFaction = opts.defenderFaction,
                })
            end
        end
    end

    -- Only the DEFENDING faction logs + displays the assault.
    if MyFaction() ~= opts.defenderFaction then return end

    local al = db.alerts[key]
    if al then
        al.lastSeen = now
        al.attacker = opts.attacker or al.attacker
    else
        al = {
            id = key, category = A.CATEGORY.WAR_EFFORT, kind = "assault",
            objId = opts.objId, shardId = shard,
            place = opts.place, zone = opts.zone,
            attacker = opts.attacker,
            attackerFaction = opts.attackerFaction,
            defenderFaction = opts.defenderFaction,
            firstSeen = now, lastSeen = now,
        }
        db.alerts[key] = al
    end

    -- Chat warning (we're the defender here), throttled per key + persisted.
    local lastChat = db.alertChat[key] or 0
    if (now - lastChat) >= CHAT_THROTTLE then
        db.alertChat[key] = now
        local zoneTxt  = al.zone and (" in " .. al.zone) or ""
        local shardTxt = al.shardId and tostring(al.shardId) or "?"
        print(("|cffff3030WarBoard Alert:|r Enemy assault reported \226\128\148 %s is attacking %s forces near %s%s! (SHARD: %s)")
            :format(tostring(al.attacker or "An enemy"), tostring(al.defenderFaction or "your"),
                    tostring(al.place or "an objective"), zoneTxt, shardTxt))
        if PlaySound then PlaySound(8959, "Master") end  -- RAID_WARNING ping
    end

    Prune()
    RefreshUI()
end

-- Point-in-time event. opts: category, kind, id, title, body. Deduped by id.
function A.AddEvent(opts)
    if not Ready() or type(opts) ~= "table" or not opts.id then return end
    if db.alerts[opts.id] then return end   -- already logged
    local now = time()
    db.alerts[opts.id] = {
        id = opts.id, category = opts.category or A.CATEGORY.SYSTEM, kind = opts.kind or "event",
        title = opts.title, body = opts.body,
        firstSeen = now, lastSeen = now,
    }
    Prune()
    RefreshUI()
end

-- Only raise live events; skip backfill (e.g. a bulk ledger/bounty sync on login
-- replaying records minutes/hours old) so the feed isn't flooded with history.
local FRESH_WINDOW = 300
local function IsFresh(t) return (not t) or (time() - t) <= FRESH_WINDOW end

-- Objective completions are intentionally NOT surfaced in the Alerts feed — it's for
-- system notices and enemy assaults, not a play-by-play of every completion (those live
-- in the Activity tab). Kept as a no-op so any older caller stays harmless.
function A.AddCompletion() end

-- Bounty posted (local or received).
function A.AddBountyPosted(b)
    if type(b) ~= "table" or not b.id then return end
    if not IsFresh(b.postedAt) then return end
    A.AddEvent({
        id = "bpost:" .. b.id, category = A.CATEGORY.BOUNTY, kind = "bounty_posted",
        title = "Bounty Posted: " .. (b.targetName or "?"),
        body = ("%s placed a bounty on %s (%s) \226\128\148 %s gold reward.")
            :format(tostring(b.posterName or "Someone"), tostring(b.targetName or "?"),
                    tostring(b.targetFaction or "?"), tostring(b.rewardGold or 0)),
    })
end

-- Your own bounty-accepts are intentionally NOT surfaced in the Alerts feed (no
-- self-spam). Kept as a no-op so any older caller stays harmless.
function A.AddBountyAccepted() end

-- System notice (campaign resets, maintenance, ...).
function A.AddSystem(id, title, body)
    A.AddEvent({ id = "sys:" .. tostring(id), category = A.CATEGORY.SYSTEM, kind = "system",
        title = title, body = body })
end

-- ── Reading / describing ───────────────────────────────────────────────────────────

function A.Status(al)
    if al.kind == "assault" then
        return ((time() - (al.lastSeen or 0)) <= ACTIVE_WINDOW) and "ACTIVE" or "RECENT"
    end
    return "EVENT"
end

local function TimeText(t)
    local d = math.max(0, time() - (t or 0))
    if d < 60    then return "Just Now" end
    if d < 3600  then return math.floor(d / 60) .. "m ago" end
    if d < 86400 then return math.floor(d / 3600) .. "h ago" end
    return math.floor(d / 86400) .. "d ago"
end
A.TimeText = TimeText

local TAG_LABEL = {
    war_effort = "WAR EFFORT",
    bounty     = "BOUNTY",
    world      = "WORLD",
    system     = "SYSTEM",
}
local CATEGORY_COLOR = {
    war_effort = { 0.95, 0.62, 0.20 },   -- amber
    bounty     = { 0.90, 0.30, 0.28 },   -- red
    world      = { 0.30, 0.74, 0.74 },   -- teal
    system     = { 0.55, 0.62, 0.78 },   -- steel
}
local STATUS_COLOR = {
    ACTIVE = { 0.95, 0.25, 0.20 },
    RECENT = { 0.85, 0.66, 0.22 },
}
-- Dark, parchment-readable headline colours per category; assaults get their own red.
local TITLE_COLOR = {
    war_effort = { 0.52, 0.30, 0.06 },
    bounty     = { 0.58, 0.13, 0.10 },
    world      = { 0.10, 0.34, 0.34 },
    system     = { 0.22, 0.27, 0.42 },
}
local ASSAULT_TITLE = { 0.62, 0.13, 0.10 }
local CHIP_BORDER   = { 0.82, 0.64, 0.34 }   -- tan bevel around the chip plate
-- Inline colour codes for the body segments.
local C_ATTACKER = "ffcf2f24"  -- red
local C_LOCATION = "ffc8a13e"  -- gold
local C_SHARD    = "ff5b8dd9"  -- blue

local function Darken(c, f) f = f or 0.42; return { c[1] * f, c[2] * f, c[3] * f } end

-- Build everything the feed row needs to render this alert, from the local viewer's
-- perspective. Returns { tag, chipFill, chipBorder, accent, title, titleColor,
-- body, timeText }.
function A.Describe(al)
    local accent = CATEGORY_COLOR[al.category] or CATEGORY_COLOR.system
    if al.kind == "assault" then
        local status   = A.Status(al)
        local place    = al.place or "an objective"
        local zoneTxt  = al.zone and (", " .. al.zone) or ""
        local shardTxt = al.shardId and tostring(al.shardId) or "?"
        local defender = al.defenderFaction or "the enemy"
        local attacker = al.attacker or "An enemy"

        -- Coloured body: attacker (red), prose (base dark), location (gold), shard
        -- (blue). "||" prints as one literal pipe separating location and shard.
        local body = ("|c%s%s|r is attacking %s forces at |c%s%s%s.|r   ||   |c%sSHARD: %s|r")
            :format(C_ATTACKER, attacker, defender, C_LOCATION, place, zoneTxt, C_SHARD, shardTxt)

        return {
            tag = status, chipFill = Darken(STATUS_COLOR[status] or STATUS_COLOR.RECENT),
            chipBorder = CHIP_BORDER, accent = accent,
            title = "ENEMY ASSAULT REPORTED", titleColor = ASSAULT_TITLE,
            body = body,
            timeText = "Last Seen: " .. TimeText(al.lastSeen),
        }
    end

    -- Event alert: category tag + stored title/body.
    return {
        tag = TAG_LABEL[al.category] or "ALERT", chipFill = Darken(accent),
        chipBorder = CHIP_BORDER, accent = accent,
        title = al.title or "Alert", titleColor = TITLE_COLOR[al.category] or TITLE_COLOR.system,
        body = al.body or "",
        timeText = TimeText(al.lastSeen),
    }
end

-- Sorted feed: ACTIVE assaults first, then everything by recency.
function A.All()
    if not Ready() then return {} end
    Prune()
    local out = {}
    for _, al in pairs(db.alerts) do out[#out + 1] = al end
    table.sort(out, function(a, b)
        local ar = (a.kind == "assault" and A.Status(a) == "ACTIVE") and 0 or 1
        local br = (b.kind == "assault" and A.Status(b) == "ACTIVE") and 0 or 1
        if ar ~= br then return ar < br end
        return (a.lastSeen or 0) > (b.lastSeen or 0)
    end)
    return out
end

function A.Count()
    if not Ready() then return 0 end
    local n = 0
    for _ in pairs(db.alerts) do n = n + 1 end
    return n
end

function A.Wipe()
    if not Ready() then return end
    wipe(db.alerts)
    wipe(db.alertChat)
    RefreshUI()
end

-- ── Init + periodic ageing tick ────────────────────────────────────────────────────
do
    local f = CreateFrame("Frame")
    f:RegisterEvent("ADDON_LOADED")
    f:SetScript("OnEvent", function(self, _, name)
        if name == addonName then EnsureDB(); self:UnregisterEvent("ADDON_LOADED") end
    end)
    -- Re-render every 30s so "Just Now" ages and ACTIVE -> RECENT transitions show.
    C_Timer.NewTicker(30, function()
        if not db then return end
        Prune()
        RefreshUI()
    end)
end
