local conform = require("conform")

local formatters_by_ft = {
  ["*"] = { "codespell", "trim_whitespace" },
  go = { "gofmt" },
  json = { "jq" },
  lua = { "stylua" },
  nix = { { "nixpkgs_fmt", "alejandra" } },
  python = { { "ruff_fix", "isort" }, { "ruff_format", "black" } },
  rust = { "rustfmt" },
  sh = { "shfmt" },
  toml = { "taplo" },
  yaml = { "yamlfix" },
}

conform.setup({
  formatters_by_ft = formatters_by_ft,
})

vim.api.nvim_create_user_command("Format", function(opts)
  conform.format({ formatters = opts.fargs })
end, {
  nargs = "+",
  complete = function()
    local names = formatters_by_ft[vim.bo.filetype] or formatters_by_ft["_"] or {}
    names = vim.list_extend(names, formatters_by_ft["*"] or {})
    names = vim.tbl_flatten(names)
    local formatters = vim.tbl_map(conform.get_formatter_info, names)
    formatters = vim.tbl_filter(function(formatter)
      return formatter.available
    end, formatters)
    return vim.tbl_map(function(formatter_info)
      return formatter_info.name
    end, formatters)
  end,
})
