#' Apply PetiContrast (Sum Coding) to a Data Frame
#'
#' This function applies a custom sum coding (effect coding) to a specified factor column
#' in a data frame. It is designed for OLS models where you want to compare each level
#' to the overall trend (mean) rather than a baseline category.
#'
#' @param data A data.frame.
#' @param col_name A string specifying the column name to transform.
#'
#' @return A data.frame with the modified contrasts for the specified column.
#' @export
#'
#' @examples
#' df <- data.frame(Quarter = factor(c("Q1", "Q2", "Q3", "Q4", "Q1", "Q2")))
#' df_new <- apply_peticontrast(df, "Quarter")
#' contrasts(df_new$Quarter)
apply_peticontrast <- function(data, col_name) {
  # 1. Ensure the column is a factor
  if (!is.factor(data[[col_name]])) {
    data[[col_name]] <- as.factor(data[[col_name]])
  }

  # 2. Get number of levels
  lvls <- levels(data[[col_name]])
  k <- length(lvls)

  if (k < 2) {
    stop("The factor must have at least 2 levels.")
  }

  # 3. Create the contrast matrix (k rows, k-1 columns)
  # 4-5. Identity matrix for the first k-1 rows
  mat <- matrix(0, nrow = k, ncol = k - 1)
  for (i in 1:(k - 1)) {
    mat[i, i] <- 1
  }

  # 6. Last row is all -1
  mat[k, ] <- -1

  # 7. Set row names
  rownames(mat) <- lvls

  # 8. Set column names dynamically
  colnames(mat) <- paste0(lvls[1:(k - 1)], "_vs_trend")

  # 9. Assign contrasts and return
  stats::contrasts(data[[col_name]]) <- mat
  return(data)
}
