-- Avante.nvim: uses Cursor ACP when the agent binary is available,
-- otherwise falls back to the Gemini API (requires GEMINI_API_KEY).
local agent_path = os.getenv("HOME") .. "/.local/bin/agent"
local has_cursor_agent = vim.uv.fs_stat(agent_path) ~= nil

local provider = has_cursor_agent and "cursor" or "gemini"

return {
	{
		"yetone/avante.nvim",
		event = "VeryLazy",
		version = false,
		build = "make",
		opts = {
			provider = provider,
			mode = "agentic",
			behaviour = {
				auto_approve_tool_permissions = {
					"web_search",
					"fetch",
					"view",
					"ls",
					"glob",
					"grep",
					"get_diagnostics",
					"think",
					"read_todos",
					"read_file_toplevel_symbols",
					"read_definitions",
				},
				auto_apply_diff_after_generation = false,
				enable_fastapply = false,
			},
			acp_providers = {
				cursor = {
					command = agent_path,
					args = { "acp" },
					auth_method = "cursor_login",
					env = {
						HOME = os.getenv("HOME"),
						PATH = os.getenv("PATH"),
					},
				},
			},
			providers = {
				gemini = {
					model = "gemini-2.5-flash",
				},
			},
		},
		config = function(_, opts)
			require("avante").setup(opts)

			vim.api.nvim_create_autocmd("FileType", {
				pattern = "AvanteInput",
				callback = function(args)
					local buf = args.buf
					local min_height = 5
					local max_height = 20

					local function resize_input()
						local win = vim.fn.bufwinid(buf)
						if win == -1 or not vim.api.nvim_win_is_valid(win) then
							return
						end
						local lines = vim.api.nvim_buf_line_count(buf)
						local height = math.max(min_height, math.min(lines + 1, max_height))
						vim.api.nvim_win_set_height(win, height)
					end

					vim.api.nvim_create_autocmd({ "TextChanged", "TextChangedI" }, {
						buffer = buf,
						callback = resize_input,
					})
					resize_input()
				end,
			})
		end,
		keys = {
			{ "<C-\\>", "<cmd>AvanteToggle<cr>", mode = { "n", "v", "i" }, desc = "Toggle Avante Chat" },
			{ "<leader>aa", "<cmd>AvanteAsk<cr>", desc = "Avante Ask" },
			{ "<leader>ae", "<cmd>AvanteEdit<cr>", desc = "Avante Edit" },
			{ "<leader>ar", "<cmd>AvanteRefresh<cr>", desc = "Avante Refresh" },
		},
		dependencies = {
			"nvim-lua/plenary.nvim",
			"MunifTanjim/nui.nvim",
			"nvim-tree/nvim-web-devicons",
			{
				"MeanderingProgrammer/render-markdown.nvim",
				opts = {
					file_types = { "markdown", "Avante" },
				},
				ft = { "markdown", "Avante" },
			},
		},
	},
}
