## ============================================================
## R Replication v3 — bug-fixed
## Issues fixed in v2:
##   - N=104 not derived (sex NA test failed)
##   - Composite discontinue all 0 (apply() row coercion issue)
##   - Japanese character matching failed (locale not set to UTF-8)
## ============================================================

# CRITICAL: Set UTF-8 locale before any string operation
Sys.setlocale("LC_ALL", "C.UTF-8")

suppressMessages({
  library(dplyr)
  library(tidyr)
  library(lme4)
  library(lmerTest)
})

DATA <- "data_for_R.csv"
TODAY <- as.Date("2026-05-06")

cat("============================================================\n")
cat("R reproduction v3 (bug-fixed)\n")
cat(sprintf("R: %s\n", R.version.string))
cat(sprintf("lme4: %s, lmerTest: %s\n",
            packageVersion("lme4"), packageVersion("lmerTest")))
cat("============================================================\n\n")

## ------------------------------------------------------------
## 1. Load and build cohort
## ------------------------------------------------------------
# na.strings is the issue — explicitly handle NA
df <- read.csv(DATA, stringsAsFactors = FALSE, na.strings = c("", "NA"),
               encoding = "UTF-8", fileEncoding = "UTF-8")
df <- df[!is.na(df$ID), ]
df$date_admit <- as.Date(df$date_admit)
df$date_dc <- as.Date(df$date_dc)
df$days_since_dc <- as.numeric(TODAY - df$date_dc)

mh <- df[df$admission_type_en == "medical_protection" &
         !is.na(df$admission_type_en), ]
elig <- mh[mh$days_since_dc >= 730 & mh$date_dc >= as.Date("2021-04-01"), ]

cat(sprintf("Cohort N=106: %d\n", nrow(elig)))

# Variables
cgas_cols <- c("cgas_t0_admit", "cgas_t1_dc", "cgas_t2_6mo",
               "cgas_t3_12mo", "cgas_t4_24mo", "cgas_t5_36mo")
for (col in cgas_cols) elig[[col]] <- as.numeric(elig[[col]])

elig$LOS_days <- as.numeric(elig$date_dc - elig$date_admit)
elig$log_LOS <- log(elig$LOS_days)
elig$ACE3 <- cut(elig$ACE_score, breaks = c(-Inf, 0, 3, Inf),
                  labels = c("0", "1-3", "ge4"))
elig$sex_male <- ifelse(elig$sex_en == "M", 1L, 0L)

# ND (vectorized version, avoiding apply() row-coercion)
nd_check <- function(v) {
  if (is.na(v) || v == "") return(FALSE)
  s <- tryCatch(as.character(as.integer(as.numeric(v))),
                warning = function(w) "", error = function(e) "")
  any(startsWith(s, c("840", "845", "849", "900")))
}
elig$ND <- as.integer(
  vapply(elig$dx_dc_1, nd_check, logical(1)) |
  vapply(elig$dx_dc_2, nd_check, logical(1)) |
  vapply(elig$dx_admit_1, nd_check, logical(1)) |
  vapply(elig$dx_admit_2, nd_check, logical(1))
)

# Composite outcome — vectorized over note column
serious_kw <- c("\u81ea\u6b7b", "\u6027\u88ab\u5bb3", "\u63aa\u7f6e\u5165\u9662",
                "\u6210\u4eba\u75c5\u68df", "mECT", "ECT", "OD",
                "\uff2f\uff24", "\uff4f\uff44")
discontinue_kw <- c("\u81ea\u5df1\u4e2d\u65ad", "\u4e2d\u65ad",
                     "\u4e0d\u660e", "\u6765\u9662\u305b\u305a",
                     "\u9023\u7d61\u306a\u3057", "\u8ee2\u533b",
                     "\u8ee2\u9662", "\u5e30\u9662\u305b\u305a",
                     "\u6025\u907d\u9000\u9662", "\u4e2d\u9014\u9000\u9662",
                     "\u8ee2\u5c45")
EXCLUDE_DROPOUT_IDS <- c(33896)

contains_any <- function(text, keywords) {
  if (is.na(text) || text == "") return(FALSE)
  any(vapply(keywords, function(k) grepl(k, text, fixed = TRUE), logical(1)))
}

note_vec <- ifelse(is.na(elig$post_dc_note), "", elig$post_dc_note)

elig$serious_event <- as.integer(
  vapply(note_vec, function(t) contains_any(t, serious_kw), logical(1))
)

is_voluntary_vec <- vapply(note_vec, function(t) {
  !is.na(t) && t != "" && grepl("\u4efb\u610f\u5165\u9662\u306b\u5909\u66f4",
                                  t, fixed = TRUE)
}, logical(1))
is_planned_vec <- vapply(note_vec, function(t) {
  if (is.na(t) || t == "") return(FALSE)
  grepl("\u7d39\u4ecb\u7d42\u4e86", t, fixed = TRUE) ||
  (grepl("\u7d4c\u904e\u826f\u597d", t, fixed = TRUE) &&
   grepl("\u7d42\u8a3a", t, fixed = TRUE)) ||
  (grepl("\u5165\u5b66", t, fixed = TRUE) &&
   grepl("\u7d42\u8a3a", t, fixed = TRUE)) ||
  grepl("\u5168\u5bee\u5236", t, fixed = TRUE)
}, logical(1))
has_disc_kw <- vapply(note_vec, function(t) contains_any(t, discontinue_kw),
                       logical(1))

elig$discontinue <- as.integer(has_disc_kw & !is_voluntary_vec & !is_planned_vec)
elig$discontinue[elig$ID %in% EXCLUDE_DROPOUT_IDS] <- 0L

elig$rehosp <- as.integer(elig$rehosp_en == "yes" & !is.na(elig$rehosp_en))
elig$Composite <- as.integer(elig$serious_event == 1L |
                              elig$rehosp == 1L |
                              elig$discontinue == 1L)
elig$seclusion <- as.integer(elig$seclusion_en == "yes" & !is.na(elig$seclusion_en))
elig$restraint <- as.integer(elig$restraint_en == "yes" & !is.na(elig$restraint_en))

# N=104 cohort
elig104 <- elig[!is.na(elig$sex_en) & !is.na(elig$age_admit), ]
cat(sprintf("Cohort N=104: %d\n\n", nrow(elig104)))

## ------------------------------------------------------------
## Composite outcome verification
## ------------------------------------------------------------
cat("============================================================\n")
cat("Composite outcome by ACE group (N=106)\n")
cat("============================================================\n")
tab_comp <- elig %>%
  group_by(ACE3) %>%
  summarise(N = n(),
            Serious = sum(serious_event),
            Rehosp = sum(rehosp),
            Discont = sum(discontinue),
            Composite = sum(Composite),
            .groups = "drop") %>%
  mutate(pct = sprintf("%.1f%%", Composite/N*100))
print(as.data.frame(tab_comp), row.names = FALSE)
cat("\nPython expected:\n")
cat("  ACE=0:   N=27, Serious=0, Rehosp=2, Discont=2,  Composite=4  (14.8%)\n")
cat("  ACE=1-3: N=34, Serious=2, Rehosp=2, Discont=6,  Composite=10 (29.4%)\n")
cat("  ACE>=4:  N=45, Serious=3, Rehosp=8, Discont=16, Composite=23 (51.1%)\n\n")

chi_test <- chisq.test(table(elig$ACE3, elig$Composite))
cat(sprintf("Chi-sq (R)      = %.3f, p = %.4f\n",
            chi_test$statistic, chi_test$p.value))
cat(sprintf("Chi-sq (Python) = 10.449, p = 0.0054\n\n"))

## ------------------------------------------------------------
## Adjusted logistic — Composite (N=104)
## ------------------------------------------------------------
cat("============================================================\n")
cat("Primary outcome 1: Composite (logistic, N=104)\n")
cat("============================================================\n")
mod_comp <- glm(Composite ~ ACE_score + sex_male + ND + age_admit,
                family = binomial, data = elig104)
s <- summary(mod_comp)$coefficients
b_ace <- s["ACE_score", "Estimate"]
se_ace <- s["ACE_score", "Std. Error"]
p_ace <- s["ACE_score", "Pr(>|z|)"]
or_ace <- exp(b_ace)
ci_l <- exp(b_ace - 1.96 * se_ace)
ci_u <- exp(b_ace + 1.96 * se_ace)
cat(sprintf("ACE OR (R)      = %.3f (95%% CI %.3f-%.3f), p = %.4f\n",
            or_ace, ci_l, ci_u, p_ace))
cat(sprintf("ACE OR (Python) = 1.370 (1.145-1.639),     p = 0.0006\n"))
m1 <- abs(or_ace - 1.370) < 0.005
cat(sprintf("Match: %s\n\n", ifelse(m1, "OK", "DIFFERS")))

## ------------------------------------------------------------
## CGAS LMM (Primary outcome 2)
## ------------------------------------------------------------
cat("============================================================\n")
cat("Primary outcome 2: CGAS LMM (N=104 base)\n")
cat("============================================================\n")
long_data <- elig104 %>%
  pivot_longer(cols = all_of(cgas_cols),
               names_to = "time_label", values_to = "CGAS") %>%
  filter(!is.na(CGAS))
time_map <- setNames(0:5, cgas_cols)
long_data$time <- factor(time_map[long_data$time_label])

mod_lmm <- lmer(CGAS ~ ACE_score + time + sex_male + ND + age_admit + (1 | ID),
                data = long_data, REML = TRUE)
s_lmm <- summary(mod_lmm)$coefficients
b_lmm <- s_lmm["ACE_score", "Estimate"]
se_lmm <- s_lmm["ACE_score", "Std. Error"]
p_lmm <- s_lmm["ACE_score", "Pr(>|t|)"]
ci_l_lmm <- b_lmm - 1.96 * se_lmm
ci_u_lmm <- b_lmm + 1.96 * se_lmm
cat(sprintf("ACE beta (R)      = %+.3f (95%% CI %+.3f to %+.3f), p = %.3f\n",
            b_lmm, ci_l_lmm, ci_u_lmm, p_lmm))
cat(sprintf("ACE beta (Python) = -0.359 (-0.922 to +0.204),     p = 0.211\n"))
m2 <- abs(b_lmm + 0.359) < 0.05
cat(sprintf("Match: %s\n\n", ifelse(m2, "OK", "DIFFERS")))

## ------------------------------------------------------------
## Length of stay
## ------------------------------------------------------------
cat("============================================================\n")
cat("Secondary: log(LOS)\n")
cat("============================================================\n")
mod_los <- lm(log_LOS ~ ACE_score + sex_male + ND + age_admit, data = elig104)
s_los <- summary(mod_los)$coefficients
b_los <- s_los["ACE_score", "Estimate"]
p_los <- s_los["ACE_score", "Pr(>|t|)"]
cat(sprintf("ACE beta (R)      = %+.3f, p = %.4f\n", b_los, p_los))
cat(sprintf("ACE beta (Python) = +0.067, p = 0.005\n\n"))

## ------------------------------------------------------------
## Seclusion / Restraint
## ------------------------------------------------------------
secl_results <- list()
for (outcome in c("seclusion", "restraint")) {
  cat(sprintf("============================================================\n"))
  cat(sprintf("Secondary: %s\n", outcome))
  cat(sprintf("============================================================\n"))
  fmla <- as.formula(paste(outcome, "~ ACE_score + sex_male + ND + age_admit"))
  mod <- glm(fmla, family = binomial, data = elig104)
  s <- summary(mod)$coefficients
  b <- s["ACE_score", "Estimate"]
  p <- s["ACE_score", "Pr(>|z|)"]
  or_v <- exp(b)
  cat(sprintf("ACE OR (R)      = %.3f, p = %.4f\n", or_v, p))
  expected_or <- if (outcome == "seclusion") 1.270 else 1.330
  expected_p <- if (outcome == "seclusion") 0.003 else 0.015
  cat(sprintf("ACE OR (Python) = %.3f, p = %.3f\n", expected_or, expected_p))
  cat("\n")
  secl_results[[outcome]] <- list(or = or_v, p = p)
}

## ------------------------------------------------------------
## Final summary
## ------------------------------------------------------------
cat("============================================================\n")
cat("FINAL REPLICATION SUMMARY\n")
cat("============================================================\n\n")
summary_table <- data.frame(
  Outcome = c("Cohort N (full)", "Cohort N (adjusted)",
              "Composite N (ACE=0)", "Composite N (ACE=1-3)", "Composite N (ACE>=4)",
              "Composite OR per 1pt ACE", "CGAS LMM beta",
              "log(LOS) beta", "Seclusion OR", "Restraint OR"),
  Python = c("106", "104",
             "4 (14.8%)", "10 (29.4%)", "23 (51.1%)",
             "1.370 (p<0.001)", "-0.359 (p=0.211)",
             "+0.067 (p=0.005)", "1.270 (p=0.003)", "1.330 (p=0.015)"),
  R = c(as.character(nrow(elig)), as.character(nrow(elig104)),
        sprintf("%d (%.1f%%)", as.numeric(tab_comp$Composite[1]), as.numeric(tab_comp$Composite[1])/27*100),
        sprintf("%d (%.1f%%)", as.numeric(tab_comp$Composite[2]), as.numeric(tab_comp$Composite[2])/34*100),
        sprintf("%d (%.1f%%)", as.numeric(tab_comp$Composite[3]), as.numeric(tab_comp$Composite[3])/45*100),
        sprintf("%.3f (p=%.4f)", or_ace, p_ace),
        sprintf("%+.3f (p=%.3f)", b_lmm, p_lmm),
        sprintf("%+.3f (p=%.4f)", b_los, p_los),
        sprintf("%.3f (p=%.4f)", secl_results$seclusion$or, secl_results$seclusion$p),
        sprintf("%.3f (p=%.4f)", secl_results$restraint$or, secl_results$restraint$p)),
  stringsAsFactors = FALSE
)
print(summary_table, row.names = FALSE)

# Save
sink("R_replication_summary.txt")
cat("R Replication Summary (v3, bug-fixed)\n")
cat("======================================\n")
cat(sprintf("Date: %s\n", format(Sys.time())))
cat(sprintf("R: %s | lme4: %s | lmerTest: %s\n\n",
            R.version.string, packageVersion("lme4"), packageVersion("lmerTest")))
print(summary_table, row.names = FALSE)
sink()

cat("\n[OK] Summary saved.\n")
