local _, GF = ...

GF.DEBUG_API_VERSION = 1

-- Search and result modules retain this table during the main addon's load.
-- The optional debug addon augments the same identity in place so those hot
-- paths do not need a permanently loaded diagnostics implementation.
GF.SearchMemoryDiagnostics = GF.SearchMemoryDiagnostics or {}

GF.DebugBridge = GF.DebugBridge or {}
local Bridge = GF.DebugBridge
local DEBUG_ADDON_NAME = "GroupFinder_Debug"

local function normalizeCommand(message)
	message = tostring(message or "")
	message = message:gsub("^%s+", ""):gsub("%s+$", "")
	return message, string.lower(message)
end

local function isDebugCommand(message)
	local raw, command = normalizeCommand(message)
	if command == "bwl" or command == "classic" or command == "seasonraid"
		or command == "testdata" or command:match("^testdata%s+")
		or command == "memdiag" or command:match("^memdiag%s+")
		or command == "screenshot" or command:match("^screenshot%s+")
		or command:match("^debug%s+")
	then
		return true
	end
	return raw == "黑翼之巢取证"
		or raw == "经典旧世取证"
		or raw == "赛季团本取证"
		or raw == "开启调试模式"
		or raw == "关闭调试模式"
		or raw == "测试数据"
		or raw == "测试数据 精简"
		or raw == "测试数据 综合"
		or raw == "测试数据 滚动"
		or raw == "英文"
		or raw == "简体中文"
		or raw == "繁体中文"
		or raw == "繁體中文"
		or raw == "调试帮助"
end

local function showStatus(message)
	if GF.ShowStatusMessage then
		GF.ShowStatusMessage(message, { semantic = true })
	elseif DEFAULT_CHAT_FRAME and DEFAULT_CHAT_FRAME.AddMessage then
		DEFAULT_CHAT_FRAME:AddMessage(tostring(message or ""))
	end
end

function Bridge:Register(debugAddon)
	if type(debugAddon) ~= "table"
		or tonumber(debugAddon.apiVersion) ~= GF.DEBUG_API_VERSION
	then
		self._loadFailure = "incompatible"
		return false
	end
	self._addon = debugAddon
	self._loadFailure = nil
	if GF.TabBar and GF.TabBar.RefreshLocale then
		GF.TabBar:RefreshLocale()
	end
	return true
end

function Bridge:IsAvailable()
	return self._addon ~= nil
		and GF.Debug ~= nil
		and type(GF.Debug.HandleSlashCommand) == "function"
end

function Bridge:Load()
	if self:IsAvailable() then
		return true
	end
	if InCombatLockdown and InCombatLockdown() then
		self._loadFailure = "combat"
		showStatus("战斗中无法加载调试组件。")
		return false
	end
	local loader = C_AddOns and C_AddOns.LoadAddOn or LoadAddOn
	if type(loader) ~= "function" then
		self._loadFailure = "loader-unavailable"
		showStatus("当前客户端无法加载调试组件。")
		return false
	end
	local ok, loaded, reason = pcall(loader, DEBUG_ADDON_NAME)
	if not ok or loaded == false or not self:IsAvailable() then
		self._loadFailure = reason or (ok and "not-registered" or "load-error")
		showStatus("调试组件未安装、未启用或版本不兼容。")
		return false
	end
	return true
end

function Bridge:HandleSlashCommand(message)
	if self:IsAvailable() then
		return GF.Debug:HandleSlashCommand(message) == true
	end
	if not isDebugCommand(message) then
		return false
	end
	if not self:Load() then
		return true
	end
	return GF.Debug:HandleSlashCommand(message) == true
end
