local T = {}

-- from astronvim util function
--- Check if a plugin is defined in lazy. Useful with lazy loading when a plugin is not necessarily loaded yet
---@param plugin string The plugin to search for
---@return boolean available # Whether the plugin is available
function T.is_available(plugin)
	return T.get_plugin(plugin) and true or false
end

-- Get the plugin file handle if it exists, return nil otherwise
function T.get_plugin(plugin)
	local status, lib = pcall(require, plugin)
	if status then
		return lib
	end
	return nil
end

-- Remove the key from the vim keymap and from being displayed in which-key
-- FIXME This does not consistently currently with which-key
-- Every once in a while the maps are correctly hidden but other times they stay?
function T.unmap_key(lhs, mode)
	mode = mode or "n"
	if T.is_available("which-key") then
		vim.keymap.set(mode, lhs, "", { desc = "which_key_ignore", silent = true })
	end
	pcall(vim.keymap.del, mode, lhs)
end

-- from https://github.com/ray-x/navigator.lua/issues/247#issue-1465308677
local function path_join(...)
	return table.concat(vim.tbl_flatten({ ... }), "/")
end
function T.set_python_env(workspace)
	local base = require("core.util").get_python_venv_basefolder(workspace)
	base = vim.fn.expand(base)
	local p = vim.env.PATH or ""
	if not base then
		return
	end
	vim.g["python3_host_prog"] = vim.fn.expand(require("core.util").get_python_venv_bin(workspace))
	vim.env.PATH = base .. "/bin:" .. p
end
function T.get_python_venv_bin(workspace)
	local pyenv = T.get_python_venv_basefolder(workspace)
	if not pyenv then
		-- Fallback to system Python.
		return vim.fn.exepath("python3") or vim.fn.exepath("python") or "python"
	end
	return path_join(pyenv, "bin", "python")
end
-- cache path so we can call it multiple times
local venv_path_cached = ""
-- return the current python environment path
function T.get_python_venv_basefolder(workspace)
	if venv_path_cached and venv_path_cached ~= "" then
		return venv_path_cached
	end

	-- Use activated virtualenv.
	if vim.env.VIRTUAL_ENV then
		venv_path_cached = vim.env.VIRTUAL_ENV
		return venv_path_cached
	end
	local match
	-- Look downwards for file, can be nested. Limit to 1 depth for speed rn
	-- TODO: Maybe not hardcode 1-depth but allow choice.
	match = vim.fn.findfile("pyvenv.cfg", "**1")
	if match ~= "" then
		match = string.gsub(match, "/pyvenv.cfg", "")
		venv_path_cached = match
		return venv_path_cached
	end
	-- Look upwards for file, it is only ever in proj root dir
	match = vim.fn.findfile("poetry.lock", (workspace or ".") .. ";")
	if match ~= "" then
		local obj = vim.system({ "poetry", "env", "info", "-p" }, { text = true }):wait()
		if obj.code ~= 0 then
			return
		end
		local venv_base_folder = obj.stdout:match("^%s*(.-)%s*$")
		venv_path_cached = venv_base_folder
		return venv_path_cached
	end
end

return T
