## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment  = "#>",
  fig.width  = 7,
  fig.height = 5,
  warning  = FALSE,
  message  = FALSE
)

## ----load-data----------------------------------------------------------------
library(drMAIC)

data(nsclc_ipd)
data(nsclc_agd)

# IPD from Study A (index trial — immunotherapy)
cat("=== Study A: IPD Summary ===\n")
cat(sprintf("n = %d patients\n", nrow(nsclc_ipd)))
cat(sprintf("Response rate: %.1f%%\n", 100 * mean(nsclc_ipd$response)))
cat(sprintf("Mean age: %.1f years\n", mean(nsclc_ipd$age)))
cat(sprintf("%% ECOG 1/2: %.1f%%\n", 100 * mean(nsclc_ipd$ecog)))
cat(sprintf("%% Ever-smoker: %.1f%%\n", 100 * mean(nsclc_ipd$smoker)))

# AgD from Study B (comparator trial)
cat("\n=== Study B: AgD ===\n")
cat(sprintf("n = %d patients\n", nsclc_agd$n_agd))
cat(sprintf("Response rate: %.1f%%\n", 100 * nsclc_agd$response_rate))
cat(sprintf("Mean age: %.1f years\n", nsclc_agd$mean_age))
cat(sprintf("%% ECOG 1/2: %.1f%%\n", 100 * nsclc_agd$prop_ecog1))
cat(sprintf("%% Ever-smoker: %.1f%%\n", 100 * nsclc_agd$prop_smoker))

## ----compute-weights----------------------------------------------------------
# Define target moments from Study B
target_moments <- c(
  age    = nsclc_agd$mean_age,
  ecog   = nsclc_agd$prop_ecog1,
  smoker = nsclc_agd$prop_smoker
)

# Compute entropy-balancing weights
w <- compute_weights(
  ipd            = nsclc_ipd,
  target_moments = target_moments,
  match_vars     = c("age", "ecog", "smoker"),
  verbose        = TRUE
)

## ----diagnostics, fig.cap="Love plot: covariate balance before and after MAIC weighting"----
diag <- maic_diagnostics(w, plot_type = "all")

## ----love-plot, fig.cap="Love Plot — covariate balance"-----------------------
diag$love_plot

## ----weight-plot, fig.cap="Weight distribution"-------------------------------
diag$weight_plot

## ----check-assumptions--------------------------------------------------------
check_assumptions(w, ess_threshold = 30, smd_threshold = 0.10)

## ----dr-maic------------------------------------------------------------------
result <- dr_maic(
  maic_weights        = w,
  outcome_var         = "response",
  outcome_type        = "binary",
  comparator_estimate = nsclc_agd$response_rate,
  comparator_se       = nsclc_agd$response_se,
  effect_measure      = "OR"
)

print(result)

## ----bootstrap, eval=FALSE----------------------------------------------------
# # Run 1000 bootstrap replicates (BCa method recommended by NICE TSD 18)
# boot_res <- bootstrap_ci(
#   dr_maic_result = result,
#   R              = 1000,
#   ci_type        = "bca",
#   seed           = 2024
# )
# print(boot_res)
# boot_res$boot_plot

## ----bootstrap-demo, echo=FALSE-----------------------------------------------
# Demonstration with fewer replicates for vignette build speed
boot_res <- bootstrap_ci(
  dr_maic_result = result,
  R              = 200,
  ci_type        = "perc",
  seed           = 2024,
  verbose        = FALSE
)
print(boot_res)

## ----sensitivity--------------------------------------------------------------
sa <- sensitivity_analysis(
  dr_maic_result   = result,
  trim_percentiles = c(0.90, 0.95, 0.99),
  lovo             = TRUE
)

## ----trim-plot, fig.cap="Weight trimming sensitivity"-------------------------
if (!is.null(sa$trim_plot)) sa$trim_plot

## ----lovo-plot, fig.cap="Leave-one-variable-out sensitivity"------------------
if (!is.null(sa$lovo_plot)) sa$lovo_plot

## ----nice-report--------------------------------------------------------------
nice_report(
  dr_maic_result   = result,
  bootstrap_result = boot_res,
  sensitivity_result = sa,
  study_a_name     = "KEYNOTE-024 (simulated)",
  study_b_name     = "IMpower150 (simulated)",
  indication       = "Advanced / Metastatic NSCLC",
  treatment_a      = "Pembrolizumab (simulated)",
  treatment_b      = "Atezo + Bev + Chemo (simulated)"
)

## ----second-moment, eval=FALSE------------------------------------------------
# w2 <- compute_weights(
#   ipd            = nsclc_ipd,
#   target_moments = c(age    = nsclc_agd$mean_age,
#                      age_sd = nsclc_agd$sd_age,
#                      ecog   = nsclc_agd$prop_ecog1,
#                      smoker = nsclc_agd$prop_smoker),
#   match_vars      = c("age", "ecog", "smoker"),
#   match_var_types = c(age = "mean_sd", ecog = "proportion", smoker = "proportion")
# )

## ----additional-covariates, eval=FALSE----------------------------------------
# result2 <- dr_maic(
#   maic_weights          = w,
#   outcome_var           = "response",
#   outcome_type          = "binary",
#   comparator_estimate   = nsclc_agd$response_rate,
#   comparator_se         = nsclc_agd$response_se,
#   additional_covariates = c("pdl1_high", "prior_lines"),  # efficiency gain
#   effect_measure        = "OR"
# )

## ----tte, eval=FALSE----------------------------------------------------------
# result_os <- dr_maic(
#   maic_weights        = w,
#   outcome_var         = "os_event",
#   outcome_type        = "tte",
#   time_var            = "os_time",
#   comparator_estimate = log(0.78),  # log-HR from comparator
#   comparator_se       = 0.12,
#   effect_measure      = "HR"
# )

