#' Interactive Data Dictionary Dictator
#'
#' @description
#' Generates roxygen2 documentation for a data frame by interactively prompting 
#' the user for a dataset title, a general description, and individual column 
#' descriptions.
#'
#' @details
#' The function performs the following steps:
#' \enumerate{
#'   \item Scans the global environment for all available data frames.
#'   \item Prompts the user to select a target data frame for documentation.
#'   \item Collects high-level metadata (title and description) for the dataset.
#'   \item Iterates through each column, displaying its type and prompting the 
#'       user for a descriptive label.
#'   \item Assembles the collected information into a CRAN-compliant roxygen2 
#'       block using the `\\describe{}` tag.
#'   \item Offers the user the choice to either print the resulting block to 
#'       the console or append it to `R/data.R`.
#' }
#'
#' @section Warning:
#' This function modifies files on disk or the global environment. Please ensure you have a backup or are using version control (e.g., Git) before execution.
#'
#' @return 
#' Invisibly returns a named list with components: \code{status} ("done",
#' "cancelled", or "error"), \code{dataset}, \code{dimensions},
#' \code{output}, and \code{roxygen_block} (character vector).
#'
#' @importFrom utils select.list
#' @examples
#' if (interactive()) {
#'   dictate_dictionary()
#' }
#' @export

dictate_dictionary <- function() {
  # Find all data frames in the global environment
  df_names <- .list_global_dataframes()
  
  if (length(df_names) == 0) {
    message("No data frames found in the global environment.")
    return(invisible(list(status = "error")))
  }
  
  # Trigger interactive prompt to select the dataset
  target_df <- select.list(
    choices = df_names,
    title = "Select a dataset to document:"
  )
  
  if (target_df == "") {
    message("Documentation cancelled.")
    return(invisible(list(status = "cancelled")))
  }
  
  data <- get(target_df, envir = .GlobalEnv)
  cols <- names(data)
  n_rows <- nrow(data)
  n_cols <- ncol(data)
  
  # Ask for high-level documentation
  message(sprintf("\n--- Documenting: '%s' (%d rows, %d columns) ---", target_df, n_rows, n_cols))
  dataset_title <- readline(prompt = "Enter a short title for this dataset: ")
  dataset_desc <- readline(prompt = "Enter a brief 1-2 sentence description: ")
  
  # Loop through columns and ask for inputs one by one
  message("\n--- Enter Column Descriptions ---")
  col_docs <- character(n_cols)
  
  for (i in seq_along(cols)) {
    col_name <- cols[i]
    col_type <- paste(class(data[[col_name]]), collapse = "/")
    
    prompt_text <- sprintf("Desc for '%s' (Type: %s): ", col_name, col_type)
    user_desc <- readline(prompt = prompt_text)
    
    if (trimws(user_desc) == "") user_desc <- "No description provided."
    
    # Format directly into roxygen \item syntax
    col_docs[i] <- sprintf("#'   \\item{%s}{%s. %s}", col_name, col_type, user_desc)
  }
  
  # Assemble the final roxygen block
  roxy_lines <- c(
    sprintf("#' %s", dataset_title),
    "#'",
    sprintf("#' %s", dataset_desc),
    "#'",
    sprintf("#' @format A data frame with %d rows and %d variables:", n_rows, n_cols),
    "#' \\describe{",
    col_docs,
    "#' }",
    sprintf("#' @source Automatically generated by Data Dictionary Dictator"),
    sprintf("\"%s\"\n", target_df)
  )
  
  # Final interactive choice for output
  message("\nDocumentation complete.")
  out_choice <- select.list(
    choices = c("Print to console", "Save to R/data.R"), 
    title = "Where should this documentation go?"
  )
  
  if (out_choice == "Print to console") {
    cat("\n--- Generated Roxygen2 Block ---\n")
    cat(roxy_lines, sep = "\n")
  } else if (out_choice == "Save to R/data.R") {
    if (!dir.exists("R")) dir.create("R")
    write(roxy_lines, file = "R/data.R", append = TRUE)
    message("Success: Documentation appended to R/data.R")
  }
  
  return(invisible(list(
    status = "done",
    dataset = target_df,
    dimensions = c(rows = n_rows, cols = n_cols),
    output = out_choice,
    roxygen_block = roxy_lines
  )))
}
