-- Autocmds are automatically loaded on the VeryLazy event
-- Default autocmds that are always set: https://github.com/LazyVim/LazyVim/blob/main/lua/lazyvim/config/autocmds.lua
-- Add any additional autocmds here

-- Aggressive fugitive auto-reload with polling
local function setup_fugitive_aggressive_reload()
  local timer = nil
  
  local function refresh_fugitive()
    -- Check all files for changes
    vim.cmd("silent! checktime")
    
    -- Force refresh any open fugitive buffers
    for _, win in ipairs(vim.api.nvim_list_wins()) do
      local buf = vim.api.nvim_win_get_buf(win)
      if vim.api.nvim_buf_get_option(buf, "filetype") == "fugitive" then
        vim.api.nvim_buf_call(buf, function()
          pcall(vim.cmd, "silent! edit")
        end)
      end
    end
  end
  
  local function start_polling()
    if timer then vim.fn.timer_stop(timer) end
    -- Poll every 2 seconds
    timer = vim.fn.timer_start(2000, function() 
      refresh_fugitive() 
    end, { ["repeat"] = -1 })
  end
  
  local function stop_polling()
    if timer then 
      vim.fn.timer_stop(timer)
      timer = nil
    end
  end
  
  local augroup = vim.api.nvim_create_augroup("FugitiveAggressiveReload", { clear = true })
  
  -- Start polling when fugitive buffer opens
  vim.api.nvim_create_autocmd("FileType", {
    group = augroup,
    pattern = "fugitive",
    callback = start_polling,
  })
  
  -- Stop polling when no fugitive buffers are open
  vim.api.nvim_create_autocmd("BufDelete", {
    group = augroup,
    callback = function()
      -- Check if any fugitive buffers remain
      local has_fugitive = false
      for _, buf in ipairs(vim.api.nvim_list_bufs()) do
        if vim.api.nvim_buf_is_valid(buf) and vim.api.nvim_buf_get_option(buf, "filetype") == "fugitive" then
          has_fugitive = true
          break
        end
      end
      if not has_fugitive then
        stop_polling()
      end
    end,
  })
end

-- Set up aggressive reload
setup_fugitive_aggressive_reload()
