-- lx-bundle:true

--- DOCX extraction commands for binary-viewer documents.
-- @module plugins.docxutils

local core = require("core")
local command = require("core.command")
local Doc = require("core.doc")
local reader = require("plugins.docxutils.reader")

local function active_docx_doc()
	local view = core.active_view
	local doc = view and view.doc
	local filename = doc and doc.filename

	if type(filename) ~= "string" then
		return nil
	end

	if filename:lower():match("%.docx$") then
		return doc
	end

	return nil
end

local function is_active_docx()
	return active_docx_doc() ~= nil
end

local function open_output_doc(source_doc, content, suffix)
	local doc = Doc.create((source_doc.filename or "untitled") .. suffix)
	core.workspace_view:open_doc(doc)

	local last_line = #doc.lines
	local last_col = #(doc.lines[last_line] or "") + 1
	doc:remove(1, 1, last_line, last_col)
	doc:insert(1, 1, content)
	doc:set_selection(1, 1)
	doc.save_disabled = true
	doc.save_disabled_reason = "generated from DOCX"
	doc:clean()
end

local function extract(mode)
	local doc = active_docx_doc()
	if not doc then
		core.error("DOCX extraction requires an active .docx binary viewer")
		return false
	end

	local content, err
	if mode == "markdown" then
		content, err = reader.extract_markdown(doc.filename)
	else
		content, err = reader.extract_text(doc.filename)
	end

	if not content then
		core.error("DOCX extraction failed: %s", tostring(err))
		return false
	end

	local suffix = mode == "markdown" and ".extracted.md" or ".extracted.txt"
	open_output_doc(doc, content, suffix)
	core.log('Extracted "%s" as %s', doc.filename, mode == "markdown" and "Markdown" or "text")
	return true
end

command.add({
	["docx:extract-text"] = {
		requires = { "binary_viewer" },
		predicate = is_active_docx,
		perform = function()
			return extract("text")
		end,
	},

	["docx:extract-md"] = {
		requires = { "binary_viewer" },
		predicate = is_active_docx,
		perform = function()
			return extract("markdown")
		end,
	},
})

return {
	read = reader.read,
	extract_text = reader.extract_text,
	extract_markdown = reader.extract_markdown,
}
