-- lx-bundle:true

local core = require("core")
local tokenizer = require("core.format.tokenizer")

local text_syntax = {}

-- Log active syntax selection details for the current document
function text_syntax.show_syntax(doc)
	local syn = doc and doc.format
	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.format 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.format, 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

return text_syntax
