# ======================================================================
# Figure 2.3. Digital infrastructure stocks by region, 2000–2025
# ======================================================================

library(dplyr)
library(readxl)
library(forcats)
library(ggplot2)
library(scales)

rm(list = ls())

# ----------------------
# Open datasets
# ----------------------

ran <- read.csv("../Data/Confidential/ran_capital_stock.csv")

datacenters <- read_excel("../Data/Confidential/datacenters_usd2024_final_november.xlsx")

submarines <- read_excel("../Data/Confidential/submarine_usd2024_final_december.xlsx")

ixps <- read_excel("../Data/Confidential/ixp_cost_per_ixp2.xlsx")

sites <- read.csv("../Data/Confidential/ran_capital_stock_new.csv")

# ----------------------
# Region recode
# ----------------------

recode_region <- function(x) {
  recode(
    x,
    "East Asia & Pacific" = "EAP",
    "Europe & Central Asia" = "ECA",
    "Latin America & Caribbean" = "LAC",
    "Middle East, North Africa, Afghanistan & Pakistan" = "MENAAP",
    "North America" = "NA",
    "Sub-Saharan Africa" = "SSA",
    "South Asia" = "SAR",
    .default = NA_character_
  )
}

allowed_codes <- c("EAP", "ECA", "LAC", "MENAAP", "NA", "SSA", "SAR")

region_colors <- c(
  "EAP" = "#1b9e77",
  "ECA" = "#d95f02",
  "LAC" = "#7570b3",
  "MENAAP" = "#ff00ff",
  "NA" = "#66a61e",
  "SSA" = "#e6ab02",
  "SAR" = "lightblue"
)

# ----------------------
# Build graph data
# ----------------------

dc <- datacenters %>%
  mutate(
    year = year_end,
    wb_region_acronym = recode_region(wb_region)
  ) %>%
  filter(wb_region_acronym %in% allowed_codes, !is.na(year)) %>%
  group_by(year, wb_region_acronym) %>%
  summarise(count = n(), .groups = "drop") %>%
  mutate(type = "Data Centers")

ct <- ran %>%
  mutate(wb_region_acronym = recode_region(wb_region)) %>%
  filter(wb_region_acronym %in% allowed_codes, !is.na(year)) %>%
  group_by(year, wb_region_acronym) %>%
  summarise(count = sum(cell_count, na.rm = TRUE), .groups = "drop") %>%
  mutate(type = "Cell Towers")

macro <- sites %>%
  mutate(wb_region_acronym = recode_region(wb_region)) %>%
  filter(wb_region_acronym %in% allowed_codes, !is.na(year)) %>%
  group_by(year, wb_region_acronym) %>%
  summarise(count = sum(macro_sites_adj, na.rm = TRUE), .groups = "drop") %>%
  mutate(type = "Macro Sites")

micro <- sites %>%
  mutate(wb_region_acronym = recode_region(wb_region)) %>%
  filter(wb_region_acronym %in% allowed_codes, !is.na(year)) %>%
  group_by(year, wb_region_acronym) %>%
  summarise(count = sum(micro_sites, na.rm = TRUE), .groups = "drop") %>%
  mutate(type = "Micro Sites")

ix <- ixps %>%
  mutate(
    year = suppressWarnings(as.integer(Established)),
    wb_region_acronym = recode_region(wb_region)
  ) %>%
  filter(wb_region_acronym %in% allowed_codes, !is.na(year)) %>%
  group_by(year, wb_region_acronym) %>%
  summarise(count = n(), .groups = "drop") %>%
  mutate(type = "IXPs")

sub <- submarines %>%
  mutate(
    year = suppressWarnings(as.integer(rfs_year)),
    wb_region_acronym = recode_region(wb_region)
  ) %>%
  filter(wb_region_acronym %in% allowed_codes, !is.na(year)) %>%
  group_by(year, wb_region_acronym) %>%
  summarise(count = n_distinct(cable_system), .groups = "drop") %>%
  mutate(type = "Submarine Cables")

infra_all <- bind_rows(dc, ct, macro, micro, ix, sub) %>%
  filter(year >= 2000, year <= 2025, !is.na(count)) %>%
  mutate(count = as.numeric(count))

region_order <- infra_all %>%
  filter(year == 2025) %>%
  group_by(wb_region_acronym) %>%
  summarise(total_2025 = sum(count, na.rm = TRUE), .groups = "drop") %>%
  arrange(desc(total_2025)) %>%
  pull(wb_region_acronym)

infra_all <- infra_all %>%
  mutate(
    wb_region_acronym = factor(wb_region_acronym, levels = region_order),
    type = fct_relevel(
      type,
      "Cell Towers",
      "Macro Sites",
      "Micro Sites",
      "Data Centers",
      "IXPs",
      "Submarine Cables"
    ),
    count_plot = case_when(
      type %in% c("Cell Towers", "Micro Sites") ~ count / 1e6,
      type == "IXPs" & count > 100 ~ 100,
      TRUE ~ count
    )
  )

# ----------------------
# Figure
# ----------------------

fig_2_3 <- ggplot(infra_all, aes(x = factor(year), y = count_plot, fill = wb_region_acronym)) +
  geom_col() +
  facet_wrap(
    ~ type,
    scales = "free_y",
    labeller = as_labeller(c(
      "Cell Towers" = "a. Mobile Cells (millions)",
      "Macro Sites" = "b. Macro Cell Sites",
      "Micro Sites" = "c. Micro Cell Sites (millions)",
      "Data Centers" = "d. Data Centers",
      "IXPs" = "e. Internet Exchange Points",
      "Submarine Cables" = "f. Submarine Cables"
    ))
  ) +
  scale_fill_manual(values = region_colors, name = "Region", drop = TRUE) +
  scale_x_discrete(
    limits = as.character(2000:2025),
    breaks = as.character(seq(2000, 2025, 5))
  ) +
  scale_y_continuous(labels = comma) +
  labs(
    x = "Year",
    y = "Count (per region-year)"
  ) +
  theme_minimal(base_size = 12) +
  theme(
    legend.position = "bottom",
    strip.text = element_text(size = 11),
    legend.title = element_text(size = 10),
    legend.text = element_text(size = 9),
    axis.text.x = element_text(angle = 45, hjust = 1)
  )

fig_2_3

ggsave("../Outputs/fig_2_3.png", plot = fig_2_3, 
       width = 15, height = 12)

