## Reproduce p3-re standalone.
suppressPackageStartupMessages({
  library(tidyverse); library(nlme); library(plm)
})
lag <- dplyr::lag; filter <- dplyr::filter; select <- dplyr::select

democracy <- read_csv("data/democracy.csv", show_col_types = FALSE) |>
  rename_with(tolower) |>
  mutate(ln_gdpw = log(gdpw))

cat("rows:", nrow(democracy), " complete:",
    sum(complete.cases(democracy[, c("ln_gdpw","reg","edt","britcol","oil","elf60","year","country")])),
    "\n")

t0 <- Sys.time()
fit_re <- tryCatch(
  lme(
    fixed       = ln_gdpw ~ reg + edt + britcol + oil + elf60,
    random      = ~ 1 | country,
    correlation = corARMA(form = ~ year | country, p = 1, q = 0),
    data        = democracy,
    na.action   = na.omit,
    method      = "REML"
  ),
  error = function(e) e$message
)
cat("elapsed:", round(as.numeric(Sys.time() - t0), 1), "s\n")

if (is.character(fit_re)) {
  cat("ERROR: ", fit_re, "\n")
} else {
  print(summary(fit_re)$tTable)
}
