-- TOG Tools
-- Author: Pimptasty
-- A collection of lightweight utility tools for WoW Classic and Retail.

local addonName, addon = ...

-- ---------------------------------------------------------------------------
-- Addon global
-- ---------------------------------------------------------------------------
TOGTools       = TOGTools or {}
TOGTools.addon = addon
addon.name     = addonName

addon.BrandColor = "ffFF8000"   -- Orange, consistent with the TOG suite

local _GetAddOnMetadata = (C_AddOns and C_AddOns.GetAddOnMetadata) or GetAddOnMetadata
addon.Version = _GetAddOnMetadata(addonName, "Version") or "dev"

-- ---------------------------------------------------------------------------
-- Version flags
-- ---------------------------------------------------------------------------
local gv = {}
addon.gameVersion = gv
do
    local tocVersion = select(4, GetBuildInfo())
    gv.isVanilla = tocVersion < 20000
    gv.isTBC     = tocVersion >= 20000 and tocVersion < 30000
    gv.isWrath   = tocVersion >= 30000 and tocVersion < 40000
    gv.isCata    = tocVersion >= 40000 and tocVersion < 50000
    gv.isMists   = tocVersion >= 50000 and tocVersion < 60000
    gv.isClassic = gv.isVanilla or gv.isTBC or gv.isWrath or gv.isCata or gv.isMists
    gv.isRetail  = not gv.isClassic
    -- Retail 12.0+ uses the EventRegistry path for chat hooks.
    gv.isRetail120Plus = tocVersion >= 120000
end

-- ---------------------------------------------------------------------------
-- AceAddon
-- ---------------------------------------------------------------------------
local Ace = LibStub("AceAddon-3.0"):NewAddon(
    addonName,
    "AceConsole-3.0",
    "AceEvent-3.0",
    "AceHook-3.0"
)
addon.lib = Ace

-- ---------------------------------------------------------------------------
-- AceDB schema
-- ---------------------------------------------------------------------------
local DB_DEFAULTS = {
    char = {
        minimapPos  = 220,
        minimapHide = false,
        frames = {
            mainWindow = { width = 640, height = 460 },
        },
        -- NamePrefix module settings (per-character — different alts may
        -- use different names/personas)
        namePrefix = {
            enabled  = true,
            nickname = "",
            format   = "(%s): ",   -- %s is replaced with nickname
            guild    = true,
            officer  = true,
            party    = false,
            raid     = false,
            instance = false,
            channel  = "",         -- custom channel name filter (empty = off)
            skipExclamation  = true,
            hideIfCharName   = false,
        },
    },
}

-- ---------------------------------------------------------------------------
-- Module registry — tabs are built from this table, sorted alphabetically
-- by their `label` field.  Each module file registers itself here.
-- ---------------------------------------------------------------------------
addon.modules = {}

-- ---------------------------------------------------------------------------
-- OnInitialize / OnEnable
-- ---------------------------------------------------------------------------
function Ace:OnInitialize()
    addon.DB = LibStub("AceDB-3.0"):New("TOGTools_DB", DB_DEFAULTS, true)

    -- Expose Version so VersionCheck-1.0 reads it from the host object directly.
    Ace.Version = addon.Version

    -- Register with VersionCheck-1.0 on Classic; the library is not yet
    -- available on Retail so we guard with the version flag.
    if not gv.isRetail then
        local VC = LibStub("VersionCheck-1.0", true)
        if VC then
            VC:Enable(Ace)
        end
    end

    -- Slash commands
    Ace:RegisterChatCommand("togtools", "SlashHandler")
    Ace:RegisterChatCommand("tt",       "SlashHandler")
end

function Ace:OnEnable()
    -- Enable all registered modules
    for _, mod in pairs(addon.modules) do
        if mod.OnEnable then mod:OnEnable() end
    end
end

function Ace:SlashHandler(input)
    input = strtrim(input or "")
    if input == "" then
        if addon.MainWindow then
            addon.MainWindow:Toggle()
        end
    elseif input == "nameprefix" or input == "np" then
        if addon.MainWindow then
            addon.MainWindow:Open("nameprefix")
        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[addonName]
            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("TOG Tools v" .. addon.Version)
        Ace:Print("/togtools (or /tt) — open the main window")
        Ace:Print("/togtools np — open Name Prefix settings")
        Ace:Print("/togtools vc — check addon versions across the guild")
    end
end
