#' @title Detect Temporal Resolution and Irregularities in Time Series
#'
#' @description
#' Determines the average temporal resolution (in minutes) of a time series vector (e.g., dendrometer timestamps)
#' and detects inconsistencies in time intervals. If the time column is character-formatted, it is automatically
#' converted to POSIXct. Any inconsistent intervals are flagged and printed.
#'
#' @details
#' This function is helpful for checking if a time series (especially dendrometer data) is regularly sampled.
#' It handles both regular and irregular timestamps and gives feedback if the resolution changes.
#'
#' @param input_time A vector of class \code{POSIXct}, \code{Date}, or \code{character}
#' representing time stamps.
#'
#' @return A single integer: the estimated (rounded) average resolution in minutes.
#'         If multiple intervals are detected, a warning and index positions are printed.
#'
#' @examples
#' \dontrun{
#' # Regular 30-minute time sequence
#' time_seq <- seq.POSIXt(from = as.POSIXct("2023-06-01 00:00:00"),
#'                        by = "30 min", length.out = 100)
#' reso_dm(time_seq)  # Should return 30
#'
#' # With character time input
#' time_char <- format(time_seq, format = "%Y-%m-%d %H:%M:%S")
#' reso_dm(time_char)  # Auto converts to POSIXct
#'
#' # Introduce an irregular step
#' time_seq[51] <- time_seq[50] + 60  # One-time 1-hour jump
#' reso_dm(time_seq)  # Should print warning and irregular step index
#' }
#'
#' @export
reso_dm <- function(input_time) {
  # Convert character time to POSIXct
  if (is.character(input_time)) {
    input_time <- lubridate::ymd_hms(input_time, quiet = TRUE)
    if (any(is.na(input_time))) {
      stop("Some timestamps could not be converted to POSIXct. Please check format.")
    }
  }

  # Validate input
  if (!inherits(input_time, "POSIXct") && !inherits(input_time, "Date")) {
    stop("Input must be a POSIXct, Date, or character vector.")
  }

  # Reference time and diff calculation
  reference <- input_time[1]
  time_min <- as.integer(difftime(input_time, reference, units = "mins"))
  diff_time <- diff(time_min)

  unique_steps <- unique(diff_time)
  avg_reso <- mean(diff_time, na.rm = TRUE)

  # Detect irregularities
  irregular_idx <- which(diff_time != stats::median(diff_time, na.rm = TRUE))

  if (length(unique_steps) > 1) {
    warning("Inconsistent time intervals detected in time series.")
    message("Unique step sizes (in minutes): ", paste(sort(unique_steps), collapse = ", "))
    if (length(irregular_idx)) {
      message("Irregular intervals found at positions: ", paste(irregular_idx, collapse = ", "))
    }
  }

  return(round(avg_reso))
}
