-- lx-bundle:true

local core = require("core")
local keymap = require("core.keymap")
local tokenizer = require("core.syntax.tokenizer")

local text_syntax = {}

-- Log active syntax selection details for the current document
function text_syntax.show_syntax(doc)
	local syn = doc and doc.syntax
	if not syn then
		core.log("No active document syntax")
		return
	end
	local is_plain = (type(syn.patterns) == "table" and #syn.patterns == 0)
		and (not syn.files or #syn.files == 0)
		and (not syn.headers or syn.headers == "")
	local module_name = syn._module_name or (is_plain and "plain_text") or tostring(syn)
	local files = (type(syn.files) == "table" and #syn.files > 0) and table.concat(syn.files, ", ") or "(none)"
	local headers = syn.headers or "(none)"
	core.log("Active syntax=%s files=%s headers=%s", module_name, files, tostring(headers))
end

-- Debug helper to show embedded syntax stack at the current line
function text_syntax.show_embedded_syntax(doc)
	if not (doc and doc.syntax and doc.highlighter) then
		core.log("No active document syntax")
		return
	end

	local line = doc:get_selection()
	local line_data = doc.highlighter:get_line(line)
	local subsyntaxes = tokenizer.extract_subsyntaxes(doc.syntax, line_data and line_data.state)
	if #subsyntaxes == 0 then
		core.log("Embedded syntaxes at line %d: (none)", line)
		return
	end

	local function syntax_debug_label(syn)
		local mod = syn._module_name
		if type(mod) == "string" and mod ~= "" and mod ~= "syntax" then
			return mod
		end
		if type(syn.shortname) == "string" and syn.shortname ~= "" then
			return syn.shortname
		end
		if type(syn.name) == "string" and syn.name ~= "" then
			return syn.name
		end
		return tostring(syn)
	end

	local labels = {}
	for i = 1, #subsyntaxes do
		local syn = subsyntaxes[i]
		labels[#labels + 1] = syntax_debug_label(syn)
	end
	core.log("Embedded syntaxes at line %d (inner->outer): %s", line, table.concat(labels, " | "))
end

-- Debug helper to inspect active wheel-related key bindings
function text_syntax.show_wheel_bindings()
	-- Formats all commands currently bound to a given keystroke
	local function cmds(stroke)
		local c = keymap.map[stroke]
		if type(c) == "table" and #c > 0 then
			return table.concat(c, ", ")
		end
		return "(none)"
	end
	core.log("wheelup=%s", cmds("wheelup"))
	core.log("wheeldown=%s", cmds("wheeldown"))
	core.log("ctrl+wheelup=%s", cmds("ctrl+wheelup"))
	core.log("ctrl+wheeldown=%s", cmds("ctrl+wheeldown"))
	core.log("ctrl+alt+wheelup=%s", cmds("ctrl+alt+wheelup"))
	core.log("ctrl+alt+wheeldown=%s", cmds("ctrl+alt+wheeldown"))
end

return text_syntax
