# 4D variable (afeall: ENDWe x ACTSa x REGr x ALLTIMEt), 2 dims fixed
# reduce_shock picks free_idx=[REGr, ALLTIMEt] (k=2, no blk)
# write_ragged: dcast row=ALLTIMEt ~ col=REGr -> 4x3 matrix
# stride ordering: antidim([REG,ALT]) = [1,3] -> write_order=[ALT,REG] (col=REG, row=ALT)
# old broken code would produce 3x4 (REG rows x ALT cols) -- detectable mismatch

time_steps <- c(0, 1, 2, 3)

dat <- ems_data(
  dat_input = dat_input,
  par_input = par_input,
  set_input = set_input,
  REG = "big3",
  ACTS = "macro_sector",
  ENDW = "labor_agg",
  time_steps = time_steps
)

model <- ems_model(
  model_file = model_file,
  closure_file = closure_file
)

REG <- c("chn", "usa", "row")
ENDW <- c("labor", "capital", "natlres", "land")
ACTS <- c("svces", "food", "crops", "mnfcs", "livestock")
ALLTIME <- seq(0, length(time_steps) - 1)

set.seed(42)

afeall_full <- expand.grid(
  ENDWe = ENDW,
  ACTSa = ACTS,
  REGr = REG,
  ALLTIMEt = ALLTIME,
  stringsAsFactors = FALSE
)
afeall_full$Value <- 0
afeall_full <- afeall_full[do.call(order, afeall_full), ]

# Fix ENDWe="natlres" AND ACTSa="crops"; free dims REGr(3) x ALLTIMEt(4), n=12
# reduce_shock: all 3-element free subsets need >=48 rows; size-2 [3,4] factor=12 matches -> k=2
afeall <- afeall_full[
  afeall_full$ENDWe == "natlres" & afeall_full$ACTSa == "crops",
]
afeall$Value <- runif(nrow(afeall))

afeall_shk <- ems_custom_shock(var = "afeall", input = afeall)


cmf_path <- ems_deploy(
  .data = dat,
  model = model,
  shock = afeall_shk
)

outputs <- ems_solve(
  cmf_path = cmf_path,
  matrix_method = "LU",
  solution_method = "Johansen"
)

# checks
afeall <- merge(afeall, afeall_full, by = setdiff(colnames(afeall), "Value"), all.y = TRUE)
afeall$Value.x <- ifelse(is.na(afeall$Value.x), afeall$Value.y, afeall$Value.x)
afeall <- afeall[, seq_len(ncol(afeall) - 1)]
colnames(afeall)[ncol(afeall)] <- "Value"

check <- all.equal(afeall, outputs$dat$afeall[, !"Year"], check.attributes = FALSE, tolerance = 1e-6)
