# Module 10: narrowly scoped, transparent teaching helpers.
# These definitions are also built inline in notes/module_10_notes.qmd.

walkers <- function(shocks, adjust_h = 0.1, adjust_m = 0.1, burn = 500L) {
  stopifnot(is.matrix(shocks), ncol(shocks) == 3L,
            all(is.finite(shocks)), burn >= 0L, burn == as.integer(burn),
            nrow(shocks) > burn + 2L,
            adjust_h >= 0, adjust_m >= 0, adjust_h + adjust_m < 2)
  n <- nrow(shocks)
  h <- m <- k <- numeric(n + 1L)
  for (t in seq_len(n)) {
    gap <- m[t] - h[t]
    h[t + 1L] <- h[t] + adjust_h * gap + shocks[t, 1L]
    m[t + 1L] <- m[t] - adjust_m * gap + shocks[t, 2L]
    k[t + 1L] <- k[t] + shocks[t, 3L]
  }
  keep <- (burn + 2L):(n + 1L)
  data.frame(t = seq_along(keep), Harry = h[keep], Mouse = m[keep],
             Karen = k[keep], gap = m[keep] - h[keep])
}

eg_cv5 <- function(n_levels) {
  # MacKinnon (2010), Table 2: N=2, tau_c (intercept, no trend).
  # n_levels-1 follows the residual-cointegration convention used by
  # statsmodels.tsa.stattools.coint. Do not substitute residual-ADF df here.
  # This teaching helper supports only the bivariate 5% constant case.
  stopifnot(length(n_levels) == 1L, is.finite(n_levels),
            n_levels == as.integer(n_levels), n_levels >= 30L)
  n_cv <- n_levels - 1L
  -3.33613 - 6.1101 / n_cv - 6.823 / n_cv^2
}

eg_test <- function(y, x, p_adf = 4L) {
  # y and x must already be complete, aligned, equally spaced observations.
  # Only an intercept in the first-stage regression; no residual intercept.
  # No ordinary lm t-test p-value is returned as a cointegration p-value.
  stopifnot(is.numeric(y), is.numeric(x), length(y) == length(x),
            all(is.finite(y)), all(is.finite(x)), sd(x) > 0,
            length(p_adf) == 1L, is.finite(p_adf), p_adf >= 0L,
            p_adf == as.integer(p_adf), length(y) > 2L * p_adf + 5L)
  n <- length(y)
  levels_fit <- lm(y ~ x)
  e <- residuals(levels_fit)
  block <- embed(diff(e), p_adf + 1L)
  adf_data <- data.frame(de = block[, 1L], e_lag = e[(p_adf + 1L):(n - 1L)])
  if (p_adf > 0L) {
    lag_names <- paste0("de_lag", seq_len(p_adf))
    adf_data[lag_names] <- as.data.frame(block[, -1L, drop = FALSE])
  }
  adf_fit <- lm(de ~ . - 1, data = adf_data)
  tau <- unname(coef(summary(adf_fit))["e_lag", "t value"])
  cv <- eg_cv5(n)
  list(levels = levels_fit, residuals = e, adf = adf_fit,
       statistic = tau, cv5 = cv, reject5 = tau < cv,
       p_adf = p_adf, n_levels = n, n_adf = nrow(adf_data))
}
