suppressPackageStartupMessages({
  library(tidyverse); library(fixest)
})
lag <- dplyr::lag; filter <- dplyr::filter

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

# Replicate the picker
maxT <- max(table(democracy$country))
ever_aut <- democracy |>
  group_by(country, ctyname) |>
  summarise(always_aut = all(reg == 0, na.rm = TRUE),
            n_obs = n(),
            n_complete = sum(!is.na(ln_gdpw) & !is.na(reg) & !is.na(edt)),
            last_obs = max(year), .groups = "drop") |>
  filter(always_aut, n_obs == maxT, n_complete == maxT, last_obs == 1990)
cat("ever_aut candidates:\n"); print(ever_aut)

fit_fe_ar <- democracy |>
  group_by(country) |> arrange(year) |>
  mutate(ln_gdpw_lag = lag(ln_gdpw)) |> ungroup() |>
  feols(ln_gdpw ~ ln_gdpw_lag + reg + edt | country,
        data = _, cluster = ~ country)

fe_ids <- as.numeric(names(fixef(fit_fe_ar)$country))
cat("\ncountries surviving FE estimation:", length(fe_ids), " of 135\n")

for (cid in ever_aut$country) {
  hit <- cid %in% fe_ids
  cat(sprintf("  id=%d (%s) in FE? %s\n",
              cid, ever_aut$ctyname[ever_aut$country==cid], hit))
}
