local default_buffer_session = function()
	local buffer_path = vim.api.nvim_buf_get_name(0) or vim.fn.tempname()
	local temp_path = vim.fn.stdpath("run") .. "/molten-sessions" .. buffer_path .. ".json"

	local dir = vim.fn.fnamemodify(temp_path, ":p:h")
	if vim.fn.getftype(dir) ~= "dir" then
		vim.fn.mkdir(dir, "p")
	end
	return temp_path
end

-- Start quarto session
local startsession = function(file, args)
	file = file or default_buffer_session()

	local path = require("core.util").get_python_venv_bin()
	if not path then
		return
	end
	vim.g["python3_host_prog"] = path

	if vim.fn.executable("jupyter-console") ~= 1 then
		return
	end

	if args then
		file = args[0]
	end
	local once = false
	vim.fn.jobstart({ "jupyter", "console", "-f", file }, {
		on_stdout = function(_)
			if not once then
				vim.cmd("MoltenInit " .. file)
			end
			once = true
		end,
		on_exit = function(_)
			vim.notify(string.format("jupyter kernel stopped: %s", file), vim.log.levels.INFO)
		end,
		stdin = nil,
	})
end
vim.api.nvim_create_user_command("JupyterStart", function()
	startsession(vim.b["sessionfile"] or default_buffer_session())
end, {})

if vim.g.quarto_auto_init_molten_session then
	vim.api.nvim_create_autocmd({ "InsertEnter", "BufEnter" }, {
		callback = function()
			if vim.b["sessionfile"] == nil then
				local path = default_buffer_session()
				vim.b["sessionfile"] = path
				vim.schedule_wrap(function()
					startsession(path)
				end)
			end
		end,
	})
end
