## ----echo=FALSE,include=FALSE-------------------------------------------------
library(redlist)
library(kableExtra)
library(dplyr)

## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  eval=FALSE,
  comment = "#>"
)

## ----setup, warning=FALSE, message=FALSE--------------------------------------
# # Define required packages
# packages <- c("rgbif", "redlist", "sf", "dplyr", "ggplot2")
# 
# # Install missing packages and load all
# for (pkg in packages) {
#   if (!requireNamespace(pkg, quietly = TRUE)) {
#     install.packages(pkg, repos = "https://packagemanager.posit.co/cran/latest")
#   }
#   library(pkg, character.only = TRUE)
# }

## ----predicates---------------------------------------------------------------
# # Temporal filter: records from 2000 onwards
# year_pred <- pred_gte("year", 2000)
# 
# # Record type filter: observational data only
# basis_of_record <- pred_in("basisOfRecord",
#                             c("MACHINE_OBSERVATION", "HUMAN_OBSERVATION"))
# 
# # Spatial quality filter: only georeferenced records
# has_coordinate <- pred("hasCoordinate", TRUE)

## ----spatial-prep-------------------------------------------------------------
# # Import park boundary shapefile
# wama_moko <- read_sf("wama_moko/wari-maro_monts kouffé.shp")
# 
# # Verify polygon validity
# st_is_valid(wama_moko)
# 
# # Merge into single polygon and simplify
# wama_moko_single <- st_union(wama_moko) %>%
#   st_simplify(dTolerance = 200) %>%
#   st_reverse() # flips the polygon vertices to follow counterclockwise

## ----crs-transform, eval=FALSE------------------------------------------------
# # Check current CRS
# st_crs(wama_moko_single)$input
# 
# # Transform to geographic coordinates
# wama_moko_single <- st_transform(wama_moko_single, crs = 4326)

## ----wkt-conversion, eval=FALSE-----------------------------------------------
# # Convert to WKT format for GBIF
# wama_moko_wkt <- st_as_text(wama_moko_single)
# 
# # Create spatial predicate
# wama_moko_pred <- pred_within(wama_moko_wkt)

## ----auth-setup---------------------------------------------------------------
# # Open .Rprofile file
# rl_open_file()

## ----download-request---------------------------------------------------------
# # Submit download request
# wama_moko_occ <- occ_download(
#   year_pred,
#   basis_of_record,
#   has_coordinate,
#   wama_moko_pred,
#   format = "SIMPLE_CSV"
# )
# 

## ----download-retrieve--------------------------------------------------------
# # Replace with your actual download key from, wama_moko_occ
# download_key <- "0007614-251120083545085"
# 
# # Wait for download to complete
# occ_download_wait(download_key)
# 
# # Retrieve and import data
# wama_moko_df <- occ_download_get(download_key) %>%
#   occ_download_import()

## ----data-filtering-----------------------------------------------------------
# species_of_interest <- wama_moko_df %>%
#   filter(phylum == "Chordata", species != "") %>%
#   distinct(species, decimalLongitude, decimalLatitude, .keep_all = TRUE) %>%
#   select(species, decimalLongitude, decimalLatitude, year)
# 
# # View processed data
# species_of_interest

## ----echo=FALSE, eval=TRUE----------------------------------------------------
 species_of_interest <- readRDS("gbif_iucn/wama_moko_species_of_interest.rds")

## ----install-ggplot2, warning=FALSE, message=FALSE, include=FALSE, eval=TRUE----
  if (!requireNamespace("ggplot2", quietly = TRUE)) {
    install.packages(pkg, dependencies = TRUE)
  }
  library(ggplot2)

## ----temporal-viz, fig.width=7, fig.height=4, fig.alt='Temporal distribution', eval=TRUE----
species_of_interest %>%
  count(year) %>%
  ggplot(aes(x = year, y = n)) +
  geom_col(fill = "gray20") +
  labs(x = "Year", y = "Number of Records") +
  scale_x_continuous(breaks = seq(2000, 2023, 1)) +
  theme_minimal() +
  theme(
    axis.text.x = element_text(angle = 90, vjust = 0.5),
    axis.text = element_text(size = 12),
    axis.title = element_text(size = 14)
  )

## ----iucn-query---------------------------------------------------------------
# # Initialize storage for unfound species
# not_found_sp <- list()
# 
# avail_sp <- unique(species_of_interest$species)
# # Query IUCN status for each species
# genus_species <- lapply(avail_sp, function(x) {
#   # Display progress
#   progress <- round(which(avail_sp == x) * 100 / length(avail_sp), 2)
#   message(paste0(progress, "%"))
# 
#   # Rate limiting to respect API constraints
#   Sys.sleep(0.5)
# 
#   # Parse genus and species names
#   splited <- strsplit(x, "\\s")[[1]]
# 
#   # Query Red List API with error handling
#   search_result <- tryCatch({
#     rl_scientific_name(
#       genus_name = trimws(splited[1]),
#       species_name = trimws(splited[2])
#     ) %>%
#       mutate(year_published = as.numeric(year_published)) %>%
#       slice_max(year_published, n = 1, with_ties = FALSE)
#   }, error = function(e) {
#     not_found_sp[[x]] <<- x
#     return(NULL)
#   })
# 
#   search_result
# })
# 

## ----echo=FALSE, eval=TRUE----------------------------------------------------
not_found_sp <- readRDS("gbif_iucn/not_found_sp.rds")
genus_species <- readRDS("gbif_iucn/genus_species.rds")

## ----eval=TRUE----------------------------------------------------------------
# Compile species with IUCN assessments
species_with_iucn <- bind_rows(genus_species)

## ----status-summary, eval=TRUE, include=FALSE---------------------------------
# Summary of IUCN Red List categories
species_with_iucn %>%
  count(red_list_category_code) %>%
  arrange(desc(n))

## ----eval=TRUE, echo=FALSE----------------------------------------------------
species_with_iucn %>%
  count(red_list_category_code) %>%
  arrange(desc(n)) %>% 
  kableExtra::kable("html") %>% 
  kableExtra::kable_styling("striped") %>% 
  kableExtra::scroll_box(width = "100%")

