required_packages <- c(
  "tidyverse",
  "readxl",
  "writexl",
  "sf",
  "xtable",
  "geosphere",
  "lwgeom",
  "tidygeocoder",
  "units"
)

for (pkg in required_packages) {
  if (!requireNamespace(pkg, quietly = TRUE)) {
    install.packages(pkg, dependencies = TRUE)
  }
  library(pkg, character.only = TRUE)
}

if (!requireNamespace("stringi", quietly = TRUE)) install.packages("stringi")
library(stringi)

##load packages
library(tidyverse)
library(readxl)
library(writexl)
library(sf)
library(xtable)
library(geosphere)
library(lwgeom)
library(dplyr)
library(ggplot2)
library(tidygeocoder)
library(units)
library(lwgeom)
# --- Base path (Output Path) ---
# Outputpath <- file.path("C:/Users/wb657580/OneDrive - WBG/INFCE Files - ReproduciblePackage/Outputs")
Outputpath <- file.path("C:/Temp/reproducibility_workspace/reviews/FR_WLD_2026_601/Report_ReproduciblePackage/Report_ReproduciblePackage/Outputs")


##get stock data

# setwd("C:/Users/wb657580/OneDrive - WBG/INFCE Files - ReproduciblePackage/Data/Raw")
setwd("C:/Temp/reproducibility_workspace/reviews/FR_WLD_2026_601/Report_ReproduciblePackage/Report_ReproduciblePackage/Data/Raw")


##get administration boundaries

ECU_admin2 <- st_read("00_Non Sectoral Data/Raw/Map/Admin2_Map/WB_GADM_ADM2.gpkg") %>% 
  filter(nam_0 == "Ecuador")

ECU_admin2 <- ECU_admin2 %>%
  mutate(
    nam_2 = case_when(
      nam_2 == "Bolivar" & nam_1 == "Manabi" ~ "Bolivar (Manabi)",
      nam_2 == "Bolivar" & nam_1 == "Carchi" ~ "Bolivar (Carchi)",
      nam_2 == "Olmedo"  & nam_1 == "Loja"   ~ "Olmedo (Loja)",
      nam_2 == "Olmedo"  & nam_1 == "Manabi" ~ "Olmedo (Manabi)",
      TRUE ~ nam_2
    )
  )


########## Code to have ECU total Stocks
##load datacenters

datacenter <- read_excel("04_AdditionalRestrictedData/datacenters_final_2026.xlsx")

datacenterECU <- datacenter %>% 
  filter(!is.na(latitude), wb_code == "ECU")

datacenterECU <- st_as_sf(
  datacenterECU,
  coords = c("longitude", "latitude"),   # column names for longitude & latitude
  crs = 4326,                 # WGS84 coordinate reference system
  remove = FALSE              # keep original lon/lat columns
)

datacenters_joinedECU <- st_join(datacenterECU, ECU_admin2)

state_datacentersECU <- datacenters_joinedECU %>%
  st_drop_geometry() %>%
  group_by(nam_2) %>%
  summarise(dc_depreciated_cost = sum(dc_depreciated_cost, na.rm = TRUE),
            total_datacenters = n())

sum(state_datacentersECU$dc_depreciated_cost)


####################
## 4. IXPS ##
####################

ixps <- read_excel("04_AdditionalRestrictedData/ixp_costs.xlsx")

##get rough coordinates based on the city

cities <- ixps %>% 
  select(City, Country) %>% 
  distinct()

geocoded <- cities %>%
  filter(Country %in% c("Ecuador")) %>%
  mutate(query = paste(City, Country, sep = ", ")   # combine into one string
  ) %>% 
  geocode(
    address = query,          # free-text query, e.g. "Fighting Bay, New Zealand"
    method = "osm",           # or "arcgis", "google", etc.
    lat = "lat",
    long = "lon",
    return_input = TRUE
  )

ixps <- ixps %>% 
  left_join(geocoded, by = c("City", "Country"))


ixp_sf <- st_as_sf(ixps %>%  filter(!is.na(lat)), coords = c("lon", "lat"), crs = 4326, remove = FALSE)

countryratioECU <- sum(datacenterECU$dc_depreciated_cost) / sum(datacenterECU$datacenters_replacement_cost24, na.rm = TRUE)


##ECU IXP

ixp_ECU <- ixp_sf %>% 
  filter(Country == "Ecuador")

ixps_joinedECU <- st_join(ixp_ECU, ECU_admin2)

state_ixpsECU <- ixps_joinedECU %>%
  st_drop_geometry() %>%
  group_by(nam_2) %>%
  summarise(ixps_total_cost = sum(Max_Cost_USD, na.rm = TRUE),
            ixps_depreciated_cost = ixps_total_cost * countryratioECU,
            total_ixps = n()) %>% 
  select(-ixps_total_cost)

sum(state_ixpsECU$ixps_depreciated_cost)

##submarine cables

###########################
## 5. Submarine cables ##
###########################

submarine <- read_excel("04_AdditionalRestrictedData/submarine_clean_data.xlsx")

##get cost ad length by landing station

current_year <- as.numeric(format(Sys.Date(), "%Y"))
discount_rate <- 0.05

# submarine <- submarine %>% 
#   mutate(
#     years_elapsed = pmax(0, current_year - rfs_year),
#     submarine_depreciated_cost_percountry_24usd = submarine_replacement_percountry_24usd * (1 - discount_rate)^years_elapsed
#   )

submarine <- submarine %>%
  group_by(cable_system, country) %>%                     # group by both system & country
  mutate(
    route_kilometers = as.numeric(route_kilometers),
    n_landings_country = n(),                             # number of landings that country has in that system
    cost_per_station = sub_country_construction_cost / n_landings_country,
    value_per_station = sub_country_depreciated_cost / n_landings_country,
    station_length = route_kilometers / n_landings_country
  ) %>%
  ungroup()

## get coordinates for cities

##get all landing points for country you want the dissagregated information for
sub_cities_ecu <- submarine %>% 
  select(city_name, country) %>%
  filter(country == "Ecuador") %>% 
  distinct()

sub_cities_ecu <- sub_cities_ecu %>%
  mutate(
    query = paste(city_name, country, sep = ", ")   # combine into one string
  )


geocoded <- sub_cities_ecu %>%
  geocode(
    address = query,          # free-text query, e.g. "Fighting Bay, New Zealand"
    method = "osm",           # or "arcgis", "google", etc.
    lat = "lat",
    long = "lon",
    return_input = TRUE
  )

## ECU
submarine_ecu <- submarine %>% 
  left_join(geocoded, by = c("city_name", "country")) %>% 
  filter(country == "Ecuador")

##add a buffer in case coordinate is right on the beach/water


sub_ecu_sf <- st_as_sf(submarine_ecu, coords = c("lon", "lat"), crs = 4326, remove = FALSE)

landing_buf <- st_buffer(sub_ecu_sf, dist = 0.005)

sub_joinedECU <- st_join(landing_buf, ECU_admin2, join = st_intersects)

##manually impute the once that did not match on an administration (because it is on island or beach)

state_subECU <- sub_joinedECU %>%
  st_drop_geometry() %>%
  group_by(nam_2) %>%
  summarise(sub_total_value = sum(value_per_station, na.rm = TRUE),
            sub_total_kilometer = sum(station_length, na.rm = TRUE))


sum(state_subECU$sub_total_value)

############
## 6. FOC ##
############

##set working diretory and combine data

lines <- st_read("04_AdditionalRestrictedData/itu_transmission_lines.geojson")
linesval <- st_read("04_AdditionalRestrictedData/itu_transmission_lines_validated.geojson")

st_make_valid(lines)
st_make_valid(linesval)

lines_all <- bind_rows(lines, linesval)

itu_no_dup <- lines_all %>% distinct(uid, .keep_all = TRUE)

##ECU
linesECU <- itu_no_dup %>% 
  filter(country == "Ecuador")

lines_keep1 <- linesECU %>%
  select(uid, project_km = distance, geometry) %>%
  mutate(project_km = as.numeric(gsub(",", "", project_km)))   # strip commas → numeric

# make admins disjoint to avoid overlap double-counting
admins_keep1 <- ECU_admin2 %>%
  select(nam_2) %>%
  group_by(nam_2) %>% summarise(.groups = "drop") %>%
  st_make_valid()

# Intersect
pieces1 <- st_intersection(lines_keep1, admins_keep1)

# Piece length (meters); drop zero-length
pieces1 <- pieces1 %>%
  mutate(
    piece_m    = as.numeric(st_length(geometry)),
    project_km = as.numeric(project_km)  # ensure numeric in case it came in as chr/fct
  ) %>%
  filter(piece_m > 0)

# Allocate each project's trusted total by proportional geometry length
alloc1 <- pieces1 %>%
  st_set_geometry(NULL) %>%
  group_by(uid) %>%
  mutate(geom_total_m = sum(piece_m)) %>%
  ungroup() %>%
  filter(geom_total_m > 0, !is.na(project_km)) %>%
  mutate(
    prop         = piece_m / geom_total_m,
    km_allocated = prop * project_km
  )

##Summarize by admin
lengths_by_admin_ecu <- alloc1 %>%
  group_by(nam_2) %>%
  summarise(total_km_foc = sum(km_allocated, na.rm = TRUE), .groups = "drop") %>%
  arrange(desc(total_km_foc))

sum(lengths_by_admin_ecu$total_km_foc)

##calculate cost per km
costs_foc <- read.csv("04_AdditionalRestrictedData/fibercables_costsestimates.csv")

#ECU
ecu_cpk <- costs_foc %>% 
  filter(country == "Ecuador")

ecu_perkm <- ecu_cpk %>% dplyr::pull(cost_per_km_estimated) %>% dplyr::first()

##apply ran depreciation ratio for Spain (pulled manually from total stock data)
countryratio_ECU_foc <- 703584783 / 1211157288 

lengths_by_admin_ecu <- lengths_by_admin_ecu %>%
  mutate(total_cost_foc = total_km_foc * ecu_perkm,
         total_depreciated_foc = total_cost_foc * countryratio_ECU_foc) %>% 
  select(-total_cost_foc)

sum(lengths_by_admin_ecu$total_depreciated_foc)


##merge all together

#########
###RAN###
#########

ran <- read.csv("04_AdditionalRestrictedData/ecuador_sites_macro_micro_costed_depr_2025.csv")

ran <- st_as_sf(
  ran,
  coords = c("lon", "lat"),   # column names for longitude & latitude
  crs = 4326,                 # WGS84 coordinate reference system
  remove = FALSE              # keep original lon/lat columns
)

ran_joined <- st_join(ran, ECU_admin2)

state_ranECU <- ran_joined %>%
  st_drop_geometry() %>%
  group_by(nam_2) %>%
  summarise(cost_depr_2025 = sum(cost_depr_2025, na.rm = TRUE),
            admin_macrosites = n()) %>% 
  rename(ran_depreciated_2025 = cost_depr_2025)

total_towers <- sum(state_ranECU$admin_macrosites)
total_depreciated <- 703584783

state_ranECU <- state_ranECU %>% 
  mutate(site_prop = admin_macrosites / total_towers,
         ran_deprciated_total = site_prop * total_depreciated)

sum(state_ranECU$ran_deprciated_total, na.rm= TRUE)

ran_merger <- state_ranECU %>% 
  select(nam_2, ran_depreciated_2025, ran_deprciated_total, admin_macrosites) %>% 
  rename(ran_depreciated_2025_v1 = ran_depreciated_2025, ran_depreciated_2025_v2 = ran_deprciated_total)


##combine

total_digital_stock_ecu_adm2 <- state_subECU %>% 
  full_join(lengths_by_admin_ecu, by = "nam_2") %>% 
  full_join(state_ixpsECU, by = "nam_2") %>% 
  full_join(state_datacentersECU, by = "nam_2") %>%
  full_join(ran_merger, by = "nam_2") %>% 
  mutate(iso3c = "ECU") %>% 
  select(iso3c, everything())

##create column with total of 4 sectors

total_digital_stock_ecu_adm2 <- total_digital_stock_ecu_adm2 %>% 
  mutate(all_depreciated =
           coalesce(dc_depreciated_cost, 0) +
           coalesce(sub_total_value, 0) +
           coalesce(ixps_depreciated_cost, 0) +
           coalesce(total_depreciated_foc, 0) +
           coalesce(ran_depreciated_2025_v2,0)
  )

################
###POPULATION###
################

pop <- read_excel("population_ecu_admin2.xlsx")

pop$nam_2_clean <- gsub("\\s*\\([^\\)]+\\)", "", pop$nam_2)

pop <- pop %>%
  mutate(
    nam_2_final = case_when(
      nam_2_clean == "Bolivar" & grepl("Manabi", nam_2) ~ nam_2,   # restore Bolivar (Manabi)
      nam_2_clean == "Bolivar" & grepl("Carchi", nam_2) ~ nam_2,   # restore Bolivar (Carchi)
      nam_2_clean == "Olmedo"  & grepl("Loja", nam_2)   ~ nam_2,   # restore Olmedo (Loja)
      nam_2_clean == "Olmedo"  & grepl("Manabi", nam_2) ~ nam_2,   # restore Olmedo (Manabi)
      
      TRUE ~ nam_2_clean
    )
  )

duplicates <- pop %>% 
  count(nam_2_final)

pop <- pop %>%
  mutate(
    nam_2_std = nam_2_final %>%
      str_squish() %>%
      str_to_lower() %>%
      stringi::stri_trans_general("Latin-ASCII")
  )

pop <- pop %>% 
  select(nam_2_std, population)

total_digital_stock_ecu_adm2 <- total_digital_stock_ecu_adm2 %>%
  mutate(
    nam_2_std = nam_2 %>%
      str_squish() %>%
      str_to_lower() %>%
      stri_trans_general("Latin-ASCII")
  )

total_digital_stock_ecu_adm2 <- total_digital_stock_ecu_adm2 %>%
  mutate(
    nam_2_std = case_when(
      # Match CityPopulation canonical strings
      
      nam_2_std == "empalme"                     ~ "el empalme",
      nam_2_std == "rioverde"                    ~ "rio verde",
      nam_2_std == "orellana"                    ~ "francisco de orellana",
      nam_2_std == "rumidahui"                  ~ "ruminahui",
      nam_2_std == "logrodo"                     ~ "logrono",
      nam_2_std == "santiago"                    ~ "santiago de mendez",
      nam_2_std == "gnral. antonio elizalde"     ~ "general antonio elizalde",
      nam_2_std == "crnel. marcelino mariduena"  ~ "coronel marcelino mariduena",
      # these two might not have a pop match; you can leave them as-is:
      # nam_2_std == "manga del cura"           ~ "manga del cura",
      # nam_2_std == "el piedrero"              ~ "el piedrero",
      
      TRUE ~ nam_2_std
    )
  )

total_digital_stock_ecu_adm2_final <- total_digital_stock_ecu_adm2 %>% 
  left_join(pop, by = c("nam_2_std"))

total_digital_stock_ecu_adm2_final <- total_digital_stock_ecu_adm2_final %>% 
  mutate(per_capita_value = all_depreciated / population)


##export the data

#options(scipen = 999, digits = 15)
#write.csv(
  #total_digital_stock_ecu_adm2_final,
  #file.path(Outputpath, "admin2_ecuador_total.csv"),
  #row.names = FALSE
#)

raw_path <- file.path("..", "..", "Data", "Raw")

## export the data
options(scipen = 999, digits = 15)

raw_path <- file.path("..", "..", "Data", "Raw")

write.csv(
  total_digital_stock_ecu_adm2_final,
  file.path(raw_path, "admin2_ecuador_total.csv"),
  row.names = FALSE
)

ECU_stocks <- read.csv(file.path(raw_path, "admin2_ecuador_total.csv"))

ECU_stocks <- read.csv("admin2_ecuador_total.csv")

##merge and convert to geo spatial

ECU_stocks <- ECU_stocks %>% 
  full_join(ECU_admin2, by = "nam_2")

ECU_stocks <- st_as_sf(ECU_stocks)


ecu_mainland <- ECU_stocks %>% 
  filter(!nam_1 %in% c("Galápagos", "Galapagos"))  # adjust name

##Total Stock

ecu_total <- ggplot(ecu_mainland) +
  geom_sf(aes(fill = all_depreciated), color = "white", size = 0.1) +
  scale_fill_viridis_c(
    option = "magma",
    trans = "log10",
    na.value = "grey90",
    name = "Total Depreciated Stock Value Digital Sector (2024 USD)",
    labels = scales::label_comma()
  ) +
  guides(fill = guide_colorbar(title.position = "top")) +
  theme_minimal() +
  theme(
    legend.position = "bottom",
    legend.title = element_text(size = 10, face = "bold"),
    legend.key.width = unit(2, "cm")
  )

ecu_total

## Per capita
ecu_percap <- ggplot(ecu_mainland) +
  geom_sf(aes(fill = per_capita_value), color = "white", size = 0.1) +
  scale_fill_viridis_c(
    option = "magma",
    trans = "log10",
    na.value = "grey90",
    name = "Total Depreciated Stock Value per capita Digital Sector (2024 USD)",
    labels = scales::label_comma()
  ) +
  guides(fill = guide_colorbar(title.position = "top")) +
  theme_minimal() +
  theme(
    legend.position = "bottom",
    legend.title = element_text(size = 10, face = "bold"),
    legend.key.width = unit(2, "cm")
  )

ecu_percap

# --- Save output (A)---

file_name <- "Figure 6.12 (A) Subnational Distribution of Digital Capital Assets in Ecuador"

ggsave(
  filename = file.path(Outputpath, paste0(file_name, ".png")),
  plot   = ecu_total,
  width  = 6,
  height = 6 * (630 / 477),
  units  = "in",
  dpi    = 300,
  scale  = 0.8   # ← try 0.7–0.9
)

ggsave(
  filename = file.path(Outputpath, paste0(file_name, ".svg")),
  plot   = ecu_total,
  width  = 6,
  height = 6 * (630 / 477),
  units  = "in",
  dpi    = 300,
  scale  = 0.8   # ← try 0.7–0.9
)
# --- Save output (B) ---

file_name <- "Figure 6.12 (B) Subnational Distribution of Digital Capital Assets in Ecuador"

ggsave(
  filename = file.path(Outputpath, paste0(file_name, ".png")),
  plot   = ecu_percap,
  width  = 6,
  height = 6 * (630 / 477),
  units  = "in",
  dpi    = 300,
  scale  = 0.8   # ← try 0.7–0.9
)

ggsave(
  filename = file.path(Outputpath, paste0(file_name, ".svg")),
  plot   = ecu_percap,
  width  = 6,
  height = 6 * (630 / 477),
  units  = "in",
  dpi    = 300,
  scale  = 0.8   # ← try 0.7–0.9
)
