vim.pack.add({
	{ src = "https://github.com/mfussenegger/nvim-lint" },
})

vim.api.nvim_create_autocmd({ "BufReadPre", "BufNewFile" }, {
	group = vim.api.nvim_create_augroup("LazyLoadNvimLint", { clear = true }),
	callback = function()
		vim.cmd("packadd lint.nvim")
		local lint = require("lint")
		lint.linters_by_ft = {
			-- brew install luacheck
			lua = { "luacheck" },
			bash = { "shellcheck" },
			sh = { "shellcheck" },
			-- brew install tflint
			terraform = { "tflint" },
			-- brew install markdownlint-cli2
			markdown = { "markdownlint-cli2" },
			-- go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.64.0
			go = { "golangcilint" },
		}
		local lint_augroup = vim.api.nvim_create_augroup("lint", { clear = true })

		vim.api.nvim_create_autocmd({ "BufEnter", "BufWritePost", "InsertLeave" }, {
			group = lint_augroup,
			callback = function()
				lint.try_lint()
			end,
		})
		vim.keymap.set("n", "<leader>l", function()
			lint.try_lint()
		end, { desc = "Trigger linting for current file" })
		vim.keymap.set("n", "<leader>d", function()
			if vim.diagnostic.config().virtual_lines then
				vim.diagnostic.config({ virtual_lines = false })
			else
				vim.diagnostic.config({
					virtual_lines = {
						current_line = true,
						format = function(diagnostic)
							local max_width = vim.api.nvim_win_get_width(0) - 15
							max_width = math.max(max_width, 30)
							local wrapped = ""
							local current_len = 0
							for word in diagnostic.message:gmatch("%S+") do
								if current_len + #word + 1 > max_width and current_len > 0 then
									wrapped = wrapped .. "\n" .. word
									current_len = #word
								else
									wrapped = wrapped == "" and word or (wrapped .. " " .. word)
									current_len = current_len + #word + 1
								end
							end
							return wrapped
						end,
					},
				})
			end
		end, { desc = "Toggle inline diagnostics" })

		vim.keymap.set("n", "<leader>cd", function()
			local line = vim.api.nvim_win_get_cursor(0)[1] - 1
			local diagnostics = vim.diagnostic.get(0, { lnum = line })

			if #diagnostics == 0 then
				vim.notify("No diagnostics on current line", vim.log.levels.WARN)
				return
			end

			local messages = {}
			for _, diag in ipairs(diagnostics) do
				table.insert(messages, diag.message)
			end

			vim.fn.setreg("+", table.concat(messages, "\n"))
			vim.notify("Copied diagnostic(s) to clipboard", vim.log.levels.INFO)
		end, { desc = "Copy diagnostic to clipboard" })
	end,
})
