# =============================================================================
#  05-clustering.R  ·  AHC on the proportions_CA row scores
# =============================================================================
#
#  Runs hierarchical clustering on the row coordinates of the proportions_CA
#  to derive an empirical urban/rural typology of Swedish municipalities.
#
#  We use FactoMineR::HCPC, which performs Ward's-method AHC on the principal
#  coordinates and picks the cluster count from the largest inertia jump.
#
#  Input:
#    data/processed/proportions_CA.rds   - CA result
#
#  Outputs:
#    data/processed/proportions_HCPC.rds  - HCPC object (dendrogram, cuts,
#                                           per-cluster descriptors)
#    data/processed/cluster_assignment.csv - municipality, code, cluster

library(tidyverse)
library(FactoMineR)

afc <- read_rds("data/processed/proportions_CA.rds")

# Ward AHC on the first 5 principal axes (~85% of inertia). consol = FALSE
# skips the k-means refinement so the partition matches the dendrogram cut.
hcpc <- HCPC(afc, nb.clust = -1, consol = FALSE, graph = FALSE, min = 3, max = 6)

cluster_df <- hcpc$data.clust |>
  rownames_to_column("municipality") |>
  select(municipality, cluster = clust) |>
  mutate(cluster = as.integer(as.character(cluster)))

write_rds(hcpc, "data/processed/proportions_HCPC.rds")
write_csv(cluster_df, "data/processed/cluster_assignment.csv")

cat("\nCluster sizes:\n"); print(table(cluster_df$cluster))
cat("\nPer-cluster paragons (most typical municipalities):\n")
for (i in seq_along(hcpc$desc.ind$para)) {
  cat("\nCluster", i, ":\n")
  print(head(hcpc$desc.ind$para[[i]], 5))
}
