local wezterm = require 'wezterm'

-- Function to get the FZF theme from the shell script
-- @return string: The FZF theme
local function get_fzf_theme()
	local handle = io.popen(os.getenv("HOME") .. "/.local/bin/script/fzf_theme")
	if not handle then
		return ""
	end
	local fzf_theme = handle:read("*a")
	handle:close()
	return fzf_theme
end

-- Function to display command history with fuzzy finder
local function show_command_history()
	local fzf_theme = get_fzf_theme()
	local command_history = "history | awk '{$1=\"\"; print substr($0,2)}'"

	-- Determine if skim (sk) is installed
	local fuzzy_command = "fzf"
	if wezterm.run_child_process({ "command", "-v", "sk" }) then
		fuzzy_command = "sk"
	end

	-- Combine the commands
	local full_command = command_history .. " | " .. fuzzy_command .. " " .. fzf_theme

	-- Run the command and get the selected history entry
	local handle = io.popen(full_command)
	if not handle then
		return
	end
	local selected_command = handle:read("*a")
	handle:close()

	-- Execute the selected command
	if selected_command and #selected_command > 0 then
		wezterm.run_child_process({ "bash", "-c", selected_command })
	end
end

-- Bind key to show command history
return {
	show_command_history = show_command_history,
}

