-- Import required modules
local wezterm = require("wezterm")

-- Define the module table
local M = {}

-- Private function to create or attach to a session
local function create_or_attach_session(branch_name, command)
	-- Get the current WezTerm window's session
	local window = wezterm.target_window()

	-- Clean branch name to use as window name
	local clean_name = branch_name:gsub("[./]", "__")

	-- Check if the tab exists and select it, otherwise create a new tab
	local tab
	for _, t in ipairs(window:tabs()) do
		if t:get_title() == clean_name then
			tab = t
			break
		end
	end
	if not tab then
		tab = window:spawn_tab({ cwd = wezterm.home_dir })
		tab:set_title(clean_name)
	end

	-- Activate the tab
	window:activate_tab(tab)

	-- Send command to the selected tab if provided
	if command then
		local pane = tab:active_pane()
		pane:send_text(command .. "\n")
	end
end

function M.apply_to_config(config)
	config.windownizer_enabled = true
end

-- Function to process input arguments and call the create_or_attach_session function
function M.run(args)
	-- Extract branch name from the first argument
	local branch_name = args[1]

	-- Extract command to send to WezTerm from the remaining arguments
	local command = table.concat(args, " ", 2)

	-- Check if branch name is provided
	if not branch_name then
		print("Branch name not provided. Exiting.")
		return
	end

	-- Call private function to create or attach to session
	create_or_attach_session(branch_name, command)
end

-- Return the module table
return M
