--[[
============================================================================
ETB Prototype - DebugSystem.lua
============================================================================
Debug and logging system for development.
============================================================================
]]--

local ADDON_NAME, NS = ...
local ETB = NS.ETB

-- Check if ETB.Debug is already a function (from Init.lua) and preserve it
-- We'll use ETB.DebugSystem for the debug table instead
if type(ETB.Debug) == "function" then
    -- Store the old Debug function as DebugFunc
    ETB.DebugFunc = ETB.Debug
end

ETB.DebugSystem = ETB.DebugSystem or {}
local Debug = ETB.DebugSystem

Debug.enabled = false
Debug.logLevel = 3  -- 0=off, 1=errors, 2=warnings, 3=info, 4=debug

function Debug:Log(level, module, msg, ...)
    if not self.enabled or level > self.logLevel then return end
    
    local colors = {
        [1] = "|cffff0000",  -- ERROR
        [2] = "|cffffff00",  -- WARN
        [3] = "|cff00ff00",  -- INFO
        [4] = "|cff00ffff",  -- DEBUG
    }
    
    local formatted = select("#", ...) > 0 and string.format(msg, ...) or msg
    print(string.format("%s[ETB:%s]|r %s", colors[level] or "", module, formatted))
end

function Debug:Error(mod, msg, ...) self:Log(1, mod, msg, ...) end
function Debug:Warn(mod, msg, ...) self:Log(2, mod, msg, ...) end
function Debug:Info(mod, msg, ...) self:Log(3, mod, msg, ...) end
function Debug:Dbg(mod, msg, ...) self:Log(4, mod, msg, ...) end

function Debug:PrintMemory()
    UpdateAddOnMemoryUsage()
    local mem = GetAddOnMemoryUsage(ADDON_NAME)
    self:Info("Memory", "%.1f KB (%.2f MB)", mem, mem/1024)
    return mem
end

SLASH_ETBDEBUG1 = "/etbd"
SlashCmdList["ETBDEBUG"] = function(msg)
    local cmd = msg:lower()
    if cmd == "on" then
        Debug.enabled = true
        print("|cff00ff00[ETB]|r Debug ON")
    elseif cmd == "off" then
        Debug.enabled = false
        print("|cff00ff00[ETB]|r Debug OFF")
    elseif cmd == "mem" then
        Debug:PrintMemory()
    elseif cmd == "api" then
        print("|cff00ff00=== API Check ===|r")
        print("C_TransmogCollection: " .. (C_TransmogCollection and "YES" or "NO"))
        print("C_TransmogSets: " .. (C_TransmogSets and "YES" or "NO"))
        if C_TransmogSets and C_TransmogSets.GetAllSets then
            local sets = C_TransmogSets.GetAllSets()
            print("  Sets available: " .. (sets and #sets or 0))
        end
    else
        print("|cff00ff00=== ETB Debug ===|r")
        print("/etbd on - Enable debug")
        print("/etbd off - Disable debug")
        print("/etbd mem - Show memory")
        print("/etbd api - Check APIs")
    end
end

-- Debug system ready (use /etbd on to enable)
