vim.pack.add({
	{ src = "https://github.com/nvim-treesitter/nvim-treesitter", version = "main" },
	{ src = "https://github.com/stevearc/conform.nvim" },
})

require("nvim-treesitter").install({
	--"zsh",
	"cmake",
	"dockerfile",
	"gitignore",
	"go",
	"gotmpl",
	"java",
	"json",
	"make",
	"regex",
	"rust",
	"terraform",
	"yaml",
})

vim.api.nvim_create_autocmd("FileType", {
	callback = function()
		pcall(vim.treesitter.start)
	end,
})

-- Default to treesitter folding
vim.opt.foldexpr = "v:lua.vim.treesitter.foldexpr()"
vim.opt.foldmethod = "expr"
vim.opt.foldtext = "> "

vim.api.nvim_create_autocmd({ "BufReadPre", "BufNewFile" }, {
	group = vim.api.nvim_create_augroup("LazyLoadConform", { clear = true }),
	callback = function()
		vim.cmd("packadd conform.nvim")
		local conform = require("conform")
		conform.setup({
			formatters_by_ft = {
				-- brew install stylua
				lua = { "stylua" },
				-- install rust
				rust = { "rustfmt" },
				-- brew install prettier
				markdown = { "markdownlint-cli2" },
				json = { "prettierd", "prettier" },
				yaml = { "yamlfmt" },
				-- install terraform
				terraform = { "terraform_fmt" },
				-- brew install shfmt
				bash = { "shfmt" },
				zsh = { "shfmt" },
				sh = { "shfmt" },
				-- brew install ruff
				python = { "ruff" },
				-- go install mvdan.cc/gofumpt@latest
				go = { "gofumpt" },
			},
			formatters = {
				prettier = {
					prepend_args = { "--prose-wrap", "always" },
				},
				shfmt = {
					prepend_args = { "-i", "4", "-ci" },
				},
				ruff = {
					prepend_args = { "--extend-select", "I" },
				},
				yamlfmt = {
					prepend_args = { "-formatter", "max_line_length=0,retain_document_start=true" },
				},
			},
			format_on_save = {
				lsp_fallback = true,
				async = false,
				timeout_ms = 3000,
			},
		})

		vim.keymap.set({ "n", "v" }, "<leader>mp", function()
			conform.format({
				lsp_fallback = true,
				async = false,
				timeout_ms = 5000,
			})
		end, { desc = "Format file or range (in visual mode)" })
	end,
})
