-- lx-bundle:true

local core = require("core")
local command = require("core.command")
local config = require("core.config")
local Doc = require("core.doc")
local hook = require("core.hook")

config.reopenlastdoc_history_size = config.reopenlastdoc_history_size or 200

local closed_doc_paths = {}

-- Returns a normalized absolute path for cross-platform comparisons
local function normalize_path(path)
	if type(path) ~= "string" or path == "" then
		return nil
	end
	local normalized = system.absolute_path(path) or path
	normalized = normalized:gsub("\\", "/"):gsub("/+", "/")
	if #normalized > 1 and not normalized:match("^%a:/$") then
		normalized = normalized:gsub("/$", "")
	end
	if normalized:match("^%a:$") then
		normalized = normalized .. "/"
	end
	if normalized:match("^%a:/") then
		normalized = normalized:lower()
	end
	return normalized
end

-- Returns true when the path is currently open in any existing doc
local function is_path_open(path)
	local target = normalize_path(path)
	if not target then
		return false
	end
	for i = 1, #core.docs do
		local doc = core.docs[i]
		if normalize_path(doc and doc.filename) == target then
			return true
		end
	end
	return false
end

-- Pushes one closed document path and trims history size to configured cap
local function push_closed_path(path)
	local normalized = normalize_path(path)
	if not normalized then
		return
	end
	closed_doc_paths[#closed_doc_paths + 1] = normalized
	local max_items = tonumber(config.reopenlastdoc_history_size) or 200
	max_items = math.max(1, math.floor(max_items))
	while #closed_doc_paths > max_items do
		table.remove(closed_doc_paths, 1)
	end
end

-- Pops the newest closed path and reopens it when still available
local function reopen_last_closed_doc()
	while #closed_doc_paths > 0 do
		local path = table.remove(closed_doc_paths)
		if not is_path_open(path) then
			local doc = Doc.open_file(path)
			if doc then
				core.workspace_view:open_doc(doc)
				return true
			end
		end
	end
	return false
end

-- Track closed docs through the core doc.close hook lifecycle
hook.add("doc.close", {
	id = "reopenlastdoc-track",
	priority = 100,
	after = function(event)
		local path = event and event.filename or nil
		if path == nil then
			return
		end
		push_closed_path(path)
	end,
})

command.add({
	["core:reopen-last-doc"] = {
		perform = function()
			return reopen_last_closed_doc()
		end,
	},
})

return true
