local addonName, SinsToolkit = ...

local CVars = {}
SinsToolkit.CVars = CVars

local CATEGORY_NAMES = {
    [0] = "Debug",
    [1] = "Graphics",
    [2] = "Console",
    [3] = "Combat",
    [4] = "Game",
    [5] = "Default",
    [6] = "Net",
    [7] = "Sound",
    [8] = "GM",
    [9] = "None",
}

local cache
local lookup
local valuesCache
local modifiedSummaryCache

local function GetAllCommands()
    if ConsoleGetAllCommands then
        return ConsoleGetAllCommands()
    end
    if C_Console and C_Console.GetAllCommands then
        return C_Console.GetAllCommands()
    end
end

local function GetCVarInfoSafe(name)
    if not name or name == "" or not C_CVar or not C_CVar.GetCVarInfo then
        return false
    end

    local ok, value, defaultValue, serverAccount, serverCharacter, locked, secure, readOnly = pcall(C_CVar.GetCVarInfo, name)
    if not ok or value == nil then
        return false
    end

    return true, value, defaultValue, serverAccount, serverCharacter, locked, secure, readOnly
end

local function ValuesMatch(a, b)
    if a == b then
        return true
    end

    local numA = tonumber(a)
    local numB = tonumber(b)
    if numA and numB then
        return numA == numB
    end

    return tostring(a or "") == tostring(b or "")
end

local function AddCVar(map, name, info)
    if not name or name == "" then
        return
    end

    local key = name:lower()
    if map[key] then
        if info and info.help and info.help ~= "" then
            map[key].description = info.help
        end
        return
    end

    local exists, value, defaultValue, serverAccount, serverCharacter, locked, secure, readOnly = GetCVarInfoSafe(name)
    if not exists then
        return
    end

    map[key] = {
        name = name,
        value = value,
        defaultValue = defaultValue,
        category = info and info.category,
        categoryName = CATEGORY_NAMES[info and info.category] or "Other",
        description = info and info.help or "",
        serverAccount = serverAccount,
        serverCharacter = serverCharacter,
        locked = locked,
        secure = secure,
        readOnly = readOnly,
        isDefault = ValuesMatch(value, defaultValue),
        searchText = (name .. " " .. (info and info.help or "") .. " " .. (CATEGORY_NAMES[info and info.category] or "")):lower(),
    }
end

function CVars:Refresh()
    valuesCache = nil
    modifiedSummaryCache = nil
    local map = {}
    local commands = GetAllCommands()

    if commands then
        for _, info in ipairs(commands) do
            if info and info.command and info.commandType == 0 and info.category ~= 0 and info.category ~= 8 then
                local lower = info.command:lower()
                if not lower:find("debug", 1, true) then
                    AddCVar(map, info.command, info)
                end
            end
        end
    end

    if SinsToolkit.CVarSeedNames then
        for name in pairs(SinsToolkit.CVarSeedNames) do
            AddCVar(map, name)
        end
    end

    cache = {}
    lookup = {}
    for _, info in pairs(map) do
        cache[#cache + 1] = info
        lookup[info.name] = info
        lookup[info.name:lower()] = info
    end

    table.sort(cache, function(a, b)
        return a.name:lower() < b.name:lower()
    end)

    return cache
end

function CVars:GetAll()
    if not cache then
        self:Refresh()
    end
    return cache or {}
end

function CVars:GetInfo(name)
    if not name or name == "" then
        return nil
    end

    if not lookup then
        self:Refresh()
    end

    local info = lookup and (lookup[name] or lookup[name:lower()])
    if not info then
        return nil
    end

    local exists, value, defaultValue, serverAccount, serverCharacter, locked, secure, readOnly = GetCVarInfoSafe(info.name)
    if exists then
        local wasDefault = info.isDefault
        info.value = value
        info.defaultValue = defaultValue
        info.serverAccount = serverAccount
        info.serverCharacter = serverCharacter
        info.locked = locked
        info.secure = secure
        info.readOnly = readOnly
        info.isDefault = ValuesMatch(value, defaultValue)
        if wasDefault ~= info.isDefault then
            valuesCache = nil
            modifiedSummaryCache = nil
        end
    end

    return info
end

function CVars:GetValues(search, modifiedOnly)
    local cacheKey = tostring(search or "") .. "\001" .. tostring(modifiedOnly == true)
    if valuesCache and valuesCache[cacheKey] then
        return valuesCache[cacheKey]
    end

    local values = { [""] = "Select a CVar" }
    local needle = (search or ""):lower()

    for _, info in ipairs(self:GetAll()) do
        if (needle == "" or info.searchText:find(needle, 1, true)) and (not modifiedOnly or not info.isDefault) then
            values[info.name] = info.isDefault and info.name or ("|cff55ff55%s|r"):format(info.name)
        end
    end

    valuesCache = valuesCache or {}
    valuesCache[cacheKey] = values
    return values
end

local function FormatCVarValue(value)
    local text = tostring(value == nil and "nil" or value)
    local lower = text:lower()
    if lower == "1" or lower == "true" or lower == "enabled" then
        return "|cff55ff55" .. text .. " (enabled)|r"
    end
    if lower == "0" or lower == "false" or lower == "disabled" then
        return "|cffffcc66" .. text .. " (disabled)|r"
    end
    return text
end

function CVars:GetModifiedSummary(limit)
    local maxRows = limit or 12
    local cacheKey = tostring(maxRows)
    if modifiedSummaryCache and modifiedSummaryCache[cacheKey] then
        return modifiedSummaryCache[cacheKey]
    end

    local modified = {}
    for _, info in ipairs(self:GetAll()) do
        if not info.isDefault then
            modified[#modified + 1] = info
        end
    end

    table.sort(modified, function(a, b)
        return a.name:lower() < b.name:lower()
    end)

    local lines = {
        "|cffd8a84aModified / Enabled CVars|r",
    }

    if #modified == 0 then
        lines[#lines + 1] = "No modified CVars found in the current client list."
    else
        local count = math.min(#modified, maxRows)
        for i = 1, count do
            local info = modified[i]
            lines[#lines + 1] = ("|cff55ff55%s|r  Current: %s  Default: %s"):format(
                info.name,
                FormatCVarValue(info.value),
                FormatCVarValue(info.defaultValue)
            )
        end
        if #modified > count then
            lines[#lines + 1] = ("Showing %d of %d modified CVars. Use Show Modified Only or search to narrow the list."):format(count, #modified)
        end
    end

    modifiedSummaryCache = modifiedSummaryCache or {}
    modifiedSummaryCache[cacheKey] = table.concat(lines, "\n")
    return modifiedSummaryCache[cacheKey]
end

function CVars:GetSummary(name)
    local info = self:GetInfo(name)
    if not info then
        return "Search for and select a CVar to view its current value, default value, and flags."
    end

    local flags = {}
    if info.readOnly then flags[#flags + 1] = "read-only" end
    if info.secure then flags[#flags + 1] = "secure" end
    if info.locked then flags[#flags + 1] = "locked" end
    if info.serverAccount then flags[#flags + 1] = "server account" end
    if info.serverCharacter then flags[#flags + 1] = "server character" end
    if #flags == 0 then flags[#flags + 1] = "editable" end

    return ("Name: %s\nCategory: %s\nStatus: %s\nCurrent: %s\nDefault: %s\nFlags: %s\n\n%s"):format(
        info.name,
        info.categoryName or "Other",
        info.isDefault and "|cff55ff55Default|r" or "|cffff5555Modified|r",
        tostring(info.value),
        tostring(info.defaultValue),
        table.concat(flags, ", "),
        info.description ~= "" and info.description or "No description provided by the WoW client."
    )
end

function CVars:SetValue(name, value)
    local info = self:GetInfo(name)
    if not info then
        return false, "Select a valid CVar first."
    end
    if info.readOnly or info.locked then
        return false, "That CVar is read-only or locked by the client."
    end
    if info.secure and InCombatLockdown and InCombatLockdown() then
        return false, "That secure CVar cannot be changed in combat."
    end
    if value == nil or value == "" then
        return false, "Enter a value before applying."
    end

    local ok, err
    if C_CVar and C_CVar.SetCVar then
        ok, err = pcall(C_CVar.SetCVar, info.name, value)
    elseif SetCVar then
        ok, err = pcall(SetCVar, info.name, value)
    else
        return false, "This client does not expose a CVar setter."
    end

    if not ok then
        return false, ("The WoW client rejected that CVar change: %s"):format(err or "unknown error")
    end

    self:Refresh()
    return true, ("Updated %s."):format(info.name)
end

function CVars:ResetToDefault(name)
    local info = self:GetInfo(name)
    if not info then
        return false, "Select a valid CVar first."
    end
    if info.defaultValue == nil then
        return false, "The WoW client did not provide a default value for that CVar."
    end

    return self:SetValue(info.name, tostring(info.defaultValue))
end
