-- utilities.lua
local ADDON_NAME, WDIGI = ...
WDIGI.Utils = WDIGI.Utils or {}
WDIGI.Constants = WDIGI.Constants or {}

------------------------------------------------------------
-- TIMESTAMP + SOURCE HELPERS
------------------------------------------------------------
local function WDIGI_GetTimestamp()
    return date("%H:%M:%S")
end

local function WDIGI_GetSource()
    -- debugstack(level, numLines, noLocals)
    -- level 4 = caller of wrapper function
    local stack = debugstack(4, 1, 0)
    if not stack then return "?" end

    -- Extract "file.lua:123"
    local file, line = stack:match("([^\\/:]+):(%d+)")
    if file and line then
        return file .. ":" .. line
    end

    return "?"
end

------------------------------------------------------------
-- CORE LOG ROUTER (NEW SYSTEM)
-- This is intentionally tiny. All filtering and level
-- definitions live in debuglevels.lua.
------------------------------------------------------------
function WDIGI.Utils.Log(level, msg)
    -- 1. Always save to the internal log (This goes to your Debug Console)
    WDIGI.Utils.AppendToDebugLog(msg)

    -- 2. ONLY print to the actual Chat Frame if the level is high enough
    -- We default to 1 (ERROR) if CurrentDebugLevel isn't set.
    local activeLevel = WDIGI.CurrentDebugLevel or 1
    if level <= activeLevel then
        print("|cff00ffff[WDIGI]:|r " .. msg)
    end
end

------------------------------------------------------------
-- TABLE DUMP
------------------------------------------------------------
function WDIGI.Utils.DebugTable(tbl, label)
    label = label or "Table"

    WDIGI.Utils.Debug("Dumping table: " .. label)

    if type(tbl) ~= "table" then
        WDIGI.Utils.Error("(not a table)")
        return
    end

    for k, v in pairs(tbl) do
        WDIGI.Utils.Debug("  " .. tostring(k) .. " = " .. tostring(v))
    end
end

------------------------------------------------------------
-- PERFORMANCE TIMER
------------------------------------------------------------
function WDIGI.Utils.Time(label, func)
    local start = debugprofilestop()
    local result = func()
    local elapsed = debugprofilestop() - start
    WDIGI.Utils.Debug(label .. " took " .. string.format("%.2f ms", elapsed))
    return result
end
