

cog <- "/vsicurl/https://data.source.coop/cboettig/carbon/Irrecoverable_Carbon_2018/Irrecoverable_C_Total_2018.tif"
greens <- c("#cce7c9", "#5bb450", "#276221")
reds <- c("#fce2dc", "#ea5a5a", "#661042")
re_alpha <- c(rep(0,5), rep(50,5))


#' create a color palette text file based on reading the min and max values from a raster.  
#' @param raster a raster file that can be read with terra
#' @param colors argument to colorRampPalette
#' @param n number of colors to use as the scale
#' @param alphas a vector of alpha values.  If less then length n, any remaining are treated as 255 (no transparency) 
generate_colormap <- function(raster, colors = c("#cce7c9", "#5bb450", "#276221"), n = 50, alphas = c(0)) {
    
    r <- terra::rast(raster)
    v <- terra::minmax(r)
    min <- v[[1]]
    max <- v[[2]]
    
    x <- grDevices::colorRampPalette(colors, bias=1, alpha=TRUE)  
    y <- x(n) |> grDevices::col2rgb(alpha=TRUE) |> t()  |> as.data.frame()

    
    alphas <- c(rep(0,5), rep(50,5))
    y$alpha[1:length(alphas)] <- alphas
    values <- seq(min, max, length.out = n)
    df <- cbind(values, y)
    df |> write.table("color.txt", quote = FALSE, col.names = FALSE, row.names = FALSE)

}
generate_colormap(cog, greens)