#!/usr/bin/env Rscript
#
# Hash userId column in a CSV dataset
#
# Produces two outputs:
#   1. *_HASHED.csv   — input with userId replaced by SHA-256 hash
#   2. *_crosswalk.csv — mapping of hashed_userId <-> original userId
#
# Usage:
#   Rscript shared/hash_userId.R --input <path_to_csv> --output-dir <output_dir>
#
# Example:
#   Rscript shared/hash_userId.R \
#     --input data/logo_exp_etl_data/main_df_logoExp_promptLvl_NONPROD_1924sample.csv \
#     --output-dir logo_exp_replication/inputs/

library(argparse)
library(readr)
library(dplyr)
library(digest)

# ============================================================================
# ARGUMENT PARSING
# ============================================================================
parser <- ArgumentParser(description = "Hash userId column in a CSV dataset")
parser$add_argument("--input", required = TRUE,
                    help = "Path to input CSV file (must contain a userId column)")
parser$add_argument("--output-dir", required = TRUE,
                    help = "Directory for output files")
args <- parser$parse_args()

input_path <- args$input
output_dir <- args$output_dir

# ============================================================================
# VALIDATION
# ============================================================================
cat("=== HASH USER ID - START ===\n")
cat("Input:", input_path, "\n")
cat("Output dir:", output_dir, "\n\n")

if (!file.exists(input_path)) {
  stop(paste("Input file not found:", input_path))
}

if (!dir.exists(output_dir)) {
  dir.create(output_dir, recursive = TRUE)
  cat("Created output directory:", output_dir, "\n")
}

# ============================================================================
# LOAD DATA
# ============================================================================
cat("Loading input data...\n")
df <- read_csv(input_path, show_col_types = FALSE)
cat("Loaded", nrow(df), "rows,", ncol(df), "columns\n")

if (!"userId" %in% names(df)) {
  stop("Input CSV must contain a 'userId' column")
}

n_users <- n_distinct(df$userId)
cat("Unique userIds:", n_users, "\n\n")

# ============================================================================
# HASH
# ============================================================================
cat("Hashing userId with SHA-256...\n")
df <- df %>%
  mutate(hashed_userId = sapply(userId, digest, algo = "sha256"))

# Build crosswalk (unique user mappings only)
crosswalk <- df %>%
  distinct(userId, hashed_userId)

cat("Crosswalk:", nrow(crosswalk), "unique user mappings\n")

# Replace userId with hashed version
df <- df %>%
  select(-userId) %>%
  rename(userId = hashed_userId) %>%
  select(userId, everything())

# ============================================================================
# OUTPUT FILE NAMES
# ============================================================================
# Derive output names from input filename
input_basename <- tools::file_path_sans_ext(basename(input_path))
hashed_filename <- file.path(output_dir, paste0(input_basename, "_HASHED.csv"))
crosswalk_filename <- file.path(output_dir, paste0(input_basename, "_crosswalk.csv"))

# ============================================================================
# SAVE
# ============================================================================
write_csv(df, hashed_filename)
cat("Saved hashed dataset to:", hashed_filename, "\n")

write_csv(crosswalk, crosswalk_filename)
cat("Saved crosswalk to:", crosswalk_filename, "\n")

cat("\nVerification:\n")
cat("  Hashed rows:", nrow(df), "\n")
cat("  userId sample:", head(df$userId, 3), "\n")
cat("  userId length:", nchar(df$userId[1]), "chars (expected 64 for SHA-256)\n")

cat("\n=== HASH USER ID - END ===\n")
