local _, addonTable = ...
---@type MK
local MK = addonTable.MK
local core = addonTable
local TRANSLATE = core.TRANSLATE or function(msg) return msg end

core.Debug = core.Debug or {}
local Debug = core.Debug

local CHAT_COLOR_SUCCESS = "ff00ff66"
local CHAT_COLOR_WARNING = "ffffaa00"
local CHAT_COLOR_ERROR = "ffff5555"

local function ColorChatText(value, color)
    value = tostring(value or "")
    if value == "" then
        return value
    end
    return string.format("|c%s%s|r", color or CHAT_COLOR_SUCCESS, value)
end

local function ColorStatusText(value, color)
    return ColorChatText(value, color)
end

local function TrimText(value)
    value = tostring(value or "")
    if strtrim then
        return strtrim(value)
    end
    return value:match("^%s*(.-)%s*$") or ""
end

local function PrintUnavailable(owner, actionLabel)
    if owner and owner.Print then
        owner:Print(ColorChatText(string.format(TRANSLATE("调试动作不可用：%s"), tostring(actionLabel or "")), CHAT_COLOR_ERROR))
    end
end

function MK:IsDebugModeEnabled()
    return self.db and self.db.global and self.db.global.debugModeEnabled == true
end

function MK:SetDebugModeEnabled(enabled)
    if not self.db or not self.db.global then
        return false
    end

    local normalizedValue = enabled == true
    if self.db.global.debugModeEnabled == normalizedValue then
        return false
    end

    self.db.global.debugModeEnabled = normalizedValue

    if self.RefreshMainTabVisibility then
        self:RefreshMainTabVisibility()
    end
    if self.RefreshMainWindow and self:IsMainWindowShown() then
        self:RefreshMainWindow("DebugModeChanged", normalizedValue and "on" or "off")
    end

    return true
end

function MK:GetDebugLocaleOverride()
    return self.db and self.db.global and self.db.global.debugLocaleOverride or nil
end

function Debug.SetDebugModeEnabled(owner, enabled)
    if not owner then
        return
    end

    owner:SetDebugModeEnabled(enabled == true)
    if enabled then
        owner:Print(ColorChatText(TRANSLATE("调试模式已开启，调试选项卡已显示。"), CHAT_COLOR_SUCCESS))
    else
        owner:Print(ColorChatText(TRANSLATE("调试模式已关闭，调试选项卡已隐藏。"), CHAT_COLOR_WARNING))
    end
end

function Debug.GetLocaleOverrideLabel(owner)
    local locale = owner and owner.GetDebugLocaleOverride and owner:GetDebugLocaleOverride() or nil
    if locale == "zhCN" then
        return ColorStatusText(TRANSLATE("简体中文"), CHAT_COLOR_SUCCESS)
    end
    if locale == "zhTW" then
        return ColorStatusText(TRANSLATE("繁体中文"), CHAT_COLOR_SUCCESS)
    end
    if locale == "enUS" or locale == "enGB" then
        return ColorStatusText(TRANSLATE("英文"), CHAT_COLOR_SUCCESS)
    end
    return TRANSLATE("客户端语言")
end

function Debug.GetStatusText(owner)
    local debugMode = owner and owner.IsDebugModeEnabled and owner:IsDebugModeEnabled()
    local debugLogging = owner and owner.IsDebugLoggingEnabled and owner:IsDebugLoggingEnabled()
    local verboseLogging = owner and owner.IsDebugVerboseLoggingEnabled and owner:IsDebugVerboseLoggingEnabled()
    local visibleText = debugMode
        and ColorStatusText(TRANSLATE("显示"), CHAT_COLOR_SUCCESS)
        or ColorStatusText(TRANSLATE("隐藏"), CHAT_COLOR_ERROR)
    local debugLoggingText = debugLogging
        and ColorStatusText(TRANSLATE("开启"), CHAT_COLOR_SUCCESS)
        or ColorStatusText(TRANSLATE("关闭"), CHAT_COLOR_ERROR)
    local verboseLoggingText = verboseLogging
        and ColorStatusText(TRANSLATE("开启"), CHAT_COLOR_SUCCESS)
        or ColorStatusText(TRANSLATE("关闭"), CHAT_COLOR_ERROR)
    return string.format(
        TRANSLATE("调试页：%s  精简日志：%s  完整日志：%s  语言：%s"),
        visibleText,
        debugLoggingText,
        verboseLoggingText,
        Debug.GetLocaleOverrideLabel(owner)
    )
end

function Debug.BuildSnapshot(owner)
    local globalSettings = owner and owner.db and owner.db.global or {}
    return table.concat({
        "debug",
        owner and owner.IsDebugModeEnabled and owner:IsDebugModeEnabled() and "1" or "0",
        owner and owner.IsDebugLoggingEnabled and owner:IsDebugLoggingEnabled() and "1" or "0",
        owner and owner.IsDebugVerboseLoggingEnabled and owner:IsDebugVerboseLoggingEnabled() and "1" or "0",
        tostring(globalSettings.debugLocaleOverride or ""),
        tostring(owner and owner.testCarpoolGroupCount or 0),
        _G.MK_MEETINGSTONE_APPLICANT_TEST_ROWS_ENABLED == true and "1" or "0",
    }, "|")
end

function Debug.SetDebugLogging(owner, enabled)
    if not (Debug.SetDebugLogMode and owner) then
        PrintUnavailable(owner, TRANSLATE("调试日志"))
        return
    end

    Debug.SetDebugLogMode(owner, enabled and "on" or "off")
end

function Debug.SetVerboseLogging(owner, enabled)
    if not (Debug.SetDebugLogMode and owner) then
        PrintUnavailable(owner, TRANSLATE("完整调试日志"))
        return
    end

    Debug.SetDebugLogMode(owner, enabled and "verbose" or "verbose off")
end

function Debug.SetLocale(owner, mode)
    if not (Debug.SetDebugLocale and owner) then
        PrintUnavailable(owner, TRANSLATE("语言覆盖"))
        return
    end

    Debug.SetDebugLocale(owner, mode)
end

function Debug.RunAction(owner, actionID, payload)
    if not owner then
        return
    end

    actionID = tostring(actionID or "")
    if actionID == "help" and Debug.PrintTestCommandHelp then
        Debug.PrintTestCommandHelp(owner)
    elseif actionID == "testData" and Debug.EnableTestData then
        Debug.EnableTestData(owner)
    elseif actionID == "testData1" and Debug.EnableTestData then
        Debug.EnableTestData(owner, 1)
    elseif actionID == "testData2" and Debug.EnableTestData then
        Debug.EnableTestData(owner, 2)
    elseif actionID == "testData3" and Debug.EnableTestData then
        Debug.EnableTestData(owner, 3)
    elseif actionID == "testDataOff" and Debug.DisableTestData then
        Debug.DisableTestData(owner)
    elseif actionID == "chars" and Debug.DumpStoredCharacters then
        Debug.DumpStoredCharacters(owner)
    elseif actionID == "group" and Debug.DumpGroupCharacters then
        Debug.DumpGroupCharacters(owner)
    elseif actionID == "teleport" and Debug.DumpDungeonTeleportMapping then
        Debug.DumpDungeonTeleportMapping(owner)
    elseif actionID == "dialog" and Debug.ShowTeleportDialog then
        Debug.ShowTeleportDialog(owner, TrimText(payload))
    elseif actionID == "account" and Debug.DebugAccountTypeLookup then
        Debug.DebugAccountTypeLookup(owner)
    elseif actionID == "accountTarget" and Debug.DebugAccountTypeLookup then
        local targetName = TrimText(payload)
        if targetName == "" then
            owner:Print(ColorChatText(TRANSLATE("请输入角色-服务器。"), CHAT_COLOR_WARNING))
            return
        end
        Debug.DebugAccountTypeLookup(owner, targetName)
    elseif actionID == "accountRefresh" and Debug.RefreshAccountTypeCache then
        Debug.RefreshAccountTypeCache(owner)
    elseif actionID == "memory" and Debug.PrintMemoryDiagnostics then
        Debug.PrintMemoryDiagnostics(owner)
    elseif actionID == "localeZh" then
        Debug.SetLocale(owner, "zh")
    elseif actionID == "localeZhTW" then
        Debug.SetLocale(owner, "zhTW")
    elseif actionID == "localeEn" then
        Debug.SetLocale(owner, "en")
    elseif actionID == "localeReset" then
        Debug.SetLocale(owner, "reset")
    else
        PrintUnavailable(owner, actionID)
    end

    if owner.RefreshMainWindow and owner:IsMainWindowShown() and owner.activeTab == "debug" then
        owner:RefreshMainWindow("DebugAction", actionID)
    end
end
