## Reproduce p2-purtest standalone.
suppressPackageStartupMessages({
  library(tidyverse); library(plm); library(tseries)
})
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),
         country_f = factor(country),
         year_f    = factor(year))

db_balanced <- democracy |>
  group_by(country) |>
  filter(!any(is.na(ln_gdpw))) |>
  ungroup()

cat("balanced N rows:", nrow(db_balanced), "\n")
cat("balanced n countries:", n_distinct(db_balanced$country), "\n")
cat("range of T:\n")
print(table(table(db_balanced$country)))

# IPS
cat("\n--- IPS ---\n")
res_ips <- tryCatch(
  purtest(ln_gdpw ~ trend, data = db_balanced,
          index = c("country", "year"),
          test = "ips", lags = "SIC", pmax = 4, exo = "trend"),
  error = function(e) e$message
)
print(res_ips)

# madwu
cat("\n--- madwu ---\n")
res_mw <- tryCatch(
  purtest(ln_gdpw ~ trend, data = db_balanced,
          index = c("country", "year"),
          test = "madwu", lags = "SIC", pmax = 4, exo = "trend"),
  error = function(e) e$message
)
print(res_mw)

# levinlin
cat("\n--- levinlin ---\n")
res_ll <- tryCatch(
  purtest(ln_gdpw ~ trend, data = db_balanced,
          index = c("country", "year"),
          test = "levinlin", lags = "SIC", pmax = 4, exo = "trend"),
  error = function(e) e$message
)
print(res_ll)

# hadri
cat("\n--- hadri ---\n")
res_h <- tryCatch(
  purtest(ln_gdpw ~ trend, data = db_balanced,
          index = c("country", "year"),
          test = "hadri", lags = "SIC", pmax = 4, exo = "intercept"),
  error = function(e) e$message
)
print(res_h)
