-- TOG Tools — Slash Commands
-- All /togt command registration and handling lives here.
-- Add new subcommands to SlashHandler as modules are added.

local _, addon = ...
local Ace = addon.lib
local gv  = addon.gameVersion

-- ---------------------------------------------------------------------------
-- Registration
-- ---------------------------------------------------------------------------
hooksecurefunc(Ace, "OnInitialize", function()
    Ace:RegisterChatCommand("togt", "SlashHandler")
end)

-- ---------------------------------------------------------------------------
-- Handler
-- ---------------------------------------------------------------------------
function Ace:SlashHandler(input)
    input = strtrim(input or "")

    if input == "" then
        -- No subcommand — toggle the main window
        if addon.MainWindow then
            addon.MainWindow:Toggle()
        end

    elseif input == "np" or input == "nameprefix" then
        if addon.MainWindow then
            addon.MainWindow:Open("nameprefix")
        end

    elseif input == "al" or input == "addonload" then
        if addon.MainWindow then
            addon.MainWindow:Open("addonload")
        end

    elseif input == "mb" or input == "mail" or input == "mailbox" then
        if addon.MainWindow then
            addon.MainWindow:Open("mailbox")
        end

    elseif input == "ld" or input == "login" or input == "digest" then
        if addon.MainWindow then
            addon.MainWindow:Open("logindigest")
        end

    elseif input == "gratz" or input == "gz" then
        if addon.MainWindow then
            addon.MainWindow:Open("gratz")
        end

    elseif input == "logs" or input == "log" then
        -- Bare /togt logs — open Logs to the last-viewed sub-tab.
        if addon.MainWindow then
            addon.MainWindow:Open("logs")
        end

    elseif input == "glcheck" then
        -- Diagnostic: print API availability + in-guild status, force
        -- a QueryGuildEventLog, then report what landed in Blizzard's
        -- buffer 2 seconds later. Used to triage empty-Guild-Log reports.
        local GuildLog = addon.logCategories and addon.logCategories["guild"]
        if GuildLog and GuildLog.Diagnose then
            GuildLog:Diagnose()
        else
            Ace:Print("|cffff5555Guild Log module not loaded.|r")
        end

    elseif input == "gldump" or input:match("^gldump%s+%d+$") then
        -- Raw SV dump of the newest N Guild Log entries (default 100).
        -- Used to triage "the UI shows N blank fields but glcheck says
        -- no blanks" reports — prints every field per entry so we can
        -- compare what's stored vs what's rendered without any
        -- formatting noise. Optional numeric arg: `/togt gldump 30`.
        local GuildLog = addon.logCategories and addon.logCategories["guild"]
        if GuildLog and GuildLog.Dump then
            local n = tonumber(input:match("^gldump%s+(%d+)$")) or 100
            GuildLog:Dump(n)
        else
            Ace:Print("|cffff5555Guild Log module not loaded.|r")
        end

    elseif input == "gbdump" or input:match("^gbdump%s+%d+$") then
        -- Raw SV dump of the newest N Guild Bank Log entries (default
        -- 100), plus a per-type breakdown of how many entries of each
        -- transaction type have a populated player name. Used to triage
        -- "Player column shows `—` for some rows" reports — tells us
        -- whether Blizzard's bank API is returning nil for `name` on
        -- certain transaction types (deposit / withdraw / move / repair
        -- / depositSummary / etc.) or only on aged entries. Optional
        -- numeric arg: `/togt gbdump 30`.
        local GuildBankLog = addon.logCategories and addon.logCategories["guildbank"]
        if GuildBankLog and GuildBankLog.Dump then
            local n = tonumber(input:match("^gbdump%s+(%d+)$")) or 100
            GuildBankLog:Dump(n)
        else
            Ace:Print("|cffff5555Guild Bank Log module not loaded.|r")
        end

    elseif input == "gbcheck" then
        -- Diagnostic: print bank API availability + guild + bank-frame
        -- state, force a per-tab QueryGuildBankLog, then report what
        -- landed in Blizzard's buffer 2 seconds later plus an
        -- instrumented ingest. Used to triage empty-Guild-Bank-Log
        -- reports — TBC / Wrath / Retail all expose slightly different
        -- behaviour around the buffer and the GUILDBANKLOG_UPDATE event.
        local GuildBankLog = addon.logCategories and addon.logCategories["guildbank"]
        if GuildBankLog and GuildBankLog.Diagnose then
            GuildBankLog:Diagnose()
        else
            Ace:Print("|cffff5555Guild Bank Log module not loaded.|r")
        end

    elseif input:match("^logs?%s+%S") or input:match("^ml$") or input == "gb"
           or input == "wl" or input == "whispers" then
        -- Sub-form: "/togt logs mail" / "/togt logs trade" / "/togt logs guild"
        -- / "/togt logs guildbank" / "/togt logs bank" / "/togt logs whispers",
        -- or the shorthands "/togt ml" → Mail, "/togt gb" → Guild Bank, and
        -- "/togt wl" / "/togt whispers" → Whispers. Deep-link via
        -- Tab.pendingSubTab which the Logs tab Draw reads + clears on first
        -- paint.
        local sub
        if input == "ml" then
            sub = "mail"
        elseif input == "gb" then
            sub = "guildbank"
        elseif input == "wl" or input == "whispers" then
            sub = "whispers"
        else
            sub = input:match("^logs?%s+(%S+)")
            -- Aliases — accept friendlier strings than the bare sub-keys.
            local map = {
                mail        = "mail",
                trade       = "trade",
                guild       = "guild",
                guildbank   = "guildbank",
                bank        = "guildbank",
                gbank       = "guildbank",
                whispers    = "whispers",
                whisper     = "whispers",
            }
            sub = map[(sub or ""):lower()]
        end
        if sub and addon.MainWindow then
            local Logs = addon.modules and addon.modules["logs"]
            if Logs then Logs.pendingSubTab = sub end
            addon.MainWindow:Open("logs")
        end

    elseif input == "itemdb" or input == "db" then
        -- Developer tool — only reachable when Developer Tools is enabled.
        -- Intentionally absent from the help list below.
        if addon.DB and addon.DB.global and addon.DB.global.devTools then
            if addon.MainWindow then addon.MainWindow:Open("itemdb") end
        else
            Ace:Print("|cffFF8000TOG Tools|r Item DB is a developer tool — enable it in Settings > General > Developer Tools.")
        end

    elseif input == "settings" or input == "config" then
        if addon.OpenSettings then
            addon:OpenSettings()
        end

    elseif input == "vc" or input == "versioncheck" then
        local VC = LibStub and LibStub:GetLibrary("VersionCheck-1.0", true)
        if gv.isRetail then
            Ace:Print("|cffff4444VersionCheck-1.0 is not available on Retail.|r")
        elseif not VC then
            Ace:Print("|cffff4444VersionCheck-1.0 not found — is the VersionCheck addon installed?|r")
        else
            local hostEntry = VC.hosts and VC.hosts[addon.name]
            if not hostEntry then
                Ace:Print("|cffff4444TOG Tools is not registered with VersionCheck-1.0.|r")
            else
                VC:FireBatch()
                Ace:Print("Version check broadcast sent — waiting 21 seconds for responses...")
                C_Timer.After(21, function()
                    local responses = hostEntry.VersionResponses or {}
                    local list = {}
                    for sender, version in pairs(responses) do
                        tinsert(list, { name = sender, version = tostring(version) })
                    end
                    table.sort(list, function(a, b)
                        local cmp = VC:CompareVersion(b.version, a.version)
                        if cmp ~= 0 then return cmp > 0 end
                        return a.name < b.name
                    end)
                    Ace:Print("Version check: " .. #list .. " guild member(s) responded")
                    for _, entry in ipairs(list) do
                        Ace:Print("  " .. entry.name .. ": " .. entry.version)
                    end
                end)
            end
        end

    else
        Ace:Print("|cffFF8000TOG Tools|r v" .. addon.Version)
        Ace:Print("/togt                — open the main window")
        Ace:Print("/togt np             — open Name Prefix settings")
        Ace:Print("/togt al             — open Addon Load monitor")
        Ace:Print("/togt mail           — open Mailbox Stale Watcher")
        Ace:Print("/togt login          — open Login Digest settings")
        Ace:Print("/togt gratz          — open the Gratz tab (alias: /togt gz)")
        Ace:Print("/togt logs           — open the Logs tab (last sub-tab)")
        Ace:Print("/togt logs mail      — open Logs > Mail (alias: /togt ml)")
        Ace:Print("/togt logs guildbank — open Logs > Guild Bank (alias: /togt gb)")
        Ace:Print("/togt logs whispers  — open Logs > Whispers (alias: /togt wl)")
        Ace:Print("/togt glcheck        — diagnose Guild Log capture (chat dump)")
        Ace:Print("/togt gldump [N]     — dump newest N Guild Log entries verbatim (default 100)")
        Ace:Print("/togt gbcheck        — diagnose Guild Bank Log capture (chat dump)")
        Ace:Print("/togt gbdump [N]     — dump newest N Guild Bank Log entries verbatim (default 100)")
        Ace:Print("/togt settings       — open addon settings")
        Ace:Print("/togt vc             — check addon versions across the guild")
    end
end
