local dnf = require("dnf")
assert(dnf.api_version == "dnf/v1", "requires dnf/v1")
assert(dnf.hooks.catalog()["dungeon.clear_announcement"], "clear announcement Hook is unavailable")

local scope = dnf.config.scope or "channel"
local color = dnf.config.color or 0xFFFFD54F
assert(scope == "channel" or scope == "instance", "scope must be channel or instance")
assert(type(color) == "number" and color >= 0 and color <= 4294967295
    and color == math.floor(color), "color must be a uint32 ARGB value")

local function duration(ms)
    if ms == nil then return "未知" end
    local seconds = math.floor(ms / 1000)
    return string.format("%d分%d秒", math.floor(seconds / 60), seconds % 60)
end

dnf.providers.register("dungeon.clear_announcement", function(ctx, plan, event)
    -- This Hook receives the full dungeon.cleared envelope.
    local data = event.data
    local channel_id = data.character.channel_id
    if scope == "channel" and channel_id <= 0 then return { enabled = false } end

    local dungeon = data.dungeon_name
    if dungeon == nil or dungeon == "" then dungeon = "副本#" .. data.dungeon_id end
    local player = data.player_name
    if player == nil or player == "" then player = "冒险家#" .. data.character.id end
    local subject = "冒险家「" .. player .. "」"
    if data.party then subject = "队伍" end

    return {
        text = "[通关] " .. subject .. "完成「" .. dungeon .. "」，用时" .. duration(data.elapsed_ms) .. "。",
        scope = scope,
        channel_id = channel_id,
        color = color
    }
end)
