-- .config/wezterm/sessionizer.lua

-- Pull in the wezterm API
local wezterm = require("wezterm")

local M = {}

-- Define utility functions
-- @param cmd: The command to run
-- @return: The output of the command
local function run_command(cmd)
	local f = io.popen(cmd)
	if not f then
		return nil, "Failed to execute command: " .. cmd
	end
	local output = f:read("*a")
	f:close()
	return output
end

-- Check if a directory is valid
-- @param directory: The directory to check
-- @return: Whether the directory is valid
local function is_directory_valid(directory)
	local fd_output = run_command("fd --min-depth 1 --max-depth 5 --type d . " .. directory)
	return fd_output ~= ""
end

-- Function to create or attach to a session
-- @param selected_name: The name of the selected directory
-- @param selected: The selected directory
local function create_or_attach_session(selected_name, selected)
	local mux = wezterm.mux
	local window, pane, workspace = mux.spawn_window({
		workspace = selected_name,
		cwd = selected,
	})
	mux.set_active_workspace(selected_name)
end

-- Main sessionizer function
-- @param window: The window to run the sessionizer in
-- @param pane: The pane to run the sessionizer in
function M.run(window, pane)
	wezterm.log_info("Selecting a directory...")
	local selected = run_command(
		"fzf --preview 'tree -C {}' --preview-window=right:50%:wrap --height=100% --border --prompt='Select a directory: ' --bind='enter:accept,ctrl-c:abort' --query='' --no-mouse"
	)

	if not selected then
		wezterm.log_error("No directory selected. Exiting.")
		return
	end

	selected = selected:gsub("^%s*(.-)%s*$", "%1")
	local selected_name = selected:gsub("%.", "_")

	if not is_directory_valid(selected) then
		wezterm.log_error("Invalid directory: " .. selected)
		return
	end

	local sessions = wezterm.mux.get_sessions()
	local found = false
	for _, session in ipairs(sessions) do
		if session.name == selected_name then
			wezterm.mux.set_active_workspace(selected_name)
			found = true
			break
		end
	end

	if not found then
		create_or_attach_session(selected_name, selected)
	end
end

return M

