local wezterm = require("wezterm") --[[@as Wezterm]]
local act = wezterm.action

local M = {}

M.merge_tables = function(a, b)
    for k, v in pairs(b) do
        if a[v] ~= nil then
            wezterm.log_warn("Duplicate config option detected: ", { old = a[k], new = b[k]})
        end
        a[k] = v
    end
end

-- Only load color schemes once; store them for later use
M.get_schemes = function()
    local schemes = wezterm.GLOBAL.color_schemes
    if schemes then
        return schemes
    end
    wezterm.GLOBAL.color_schemes = wezterm.get_builtin_color_schemes()
    return wezterm.GLOBAL.color_schemes
end

-- Mimicks the show_last_command_output command in Kitty
-- Spawns the pager in a new tab since Wezterm (for now) lacks overlays
-- This function is meant to be used as a keybinding callback
M.open_last_output_in_less = function(window, pane)
    -- Grab the last nonempty "output" semantic zone
    local zones = pane:get_semantic_zones("Output")
    local last_output = ""
    local idx = #zones
    while true do
        if idx == 0 then
            break
        end
        last_output = pane:get_text_from_semantic_zone(zones[idx])
        if last_output ~= "" then
            break
        end
        idx = idx - 1
    end

    -- Ensure any quotes in output are properly escaped
    -- This is because we need to use sh/echo as a hackaround for wezterm not supporting passing stdin to
    -- commands spawned in a new tab/window
    -- See this StackOverflow question/answer for why this particular substitution works: https://stackoverflow.com/a/1315213
    last_output = last_output:gsub("'", "'\\''")

    -- Spawn less in a new tab
    local action = act.SpawnCommandInNewTab({ args = { "sh", "-c", "echo '" .. last_output .. "' | less -R" } })
    window:perform_action(action, pane)
end

return M
