library(tidyverse)
## Warning: package 'tidyverse' was built under R version 4.5.3
## Warning: package 'ggplot2' was built under R version 4.5.3
## Warning: package 'tibble' was built under R version 4.5.3
## Warning: package 'tidyr' was built under R version 4.5.3
## Warning: package 'readr' was built under R version 4.5.3
## Warning: package 'purrr' was built under R version 4.5.3
## Warning: package 'dplyr' was built under R version 4.5.3
## Warning: package 'stringr' was built under R version 4.5.3
## Warning: package 'lubridate' was built under R version 4.5.3
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.2.1     ✔ readr     2.2.0
## ✔ forcats   1.0.1     ✔ stringr   1.6.0
## ✔ ggplot2   4.0.4     ✔ tibble    3.3.1
## ✔ lubridate 1.9.5     ✔ tidyr     1.3.2
## ✔ purrr     1.2.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(readxl)
## Warning: package 'readxl' was built under R version 4.5.3
library(lubridate)

# Standardise names across all datasets
clean_names_text <- function(x) {
  x %>%
    str_squish() %>%
    str_to_lower() %>%
    str_replace_all("\\s+", "_")
}

# Import every catch-log sheet and combine them
catch_file <- here::here(
  "data", "workshop2", "estuary_catch_log.xlsx"
)

catch_clean <- excel_sheets(catch_file) %>%
  map_dfr(~ read_excel(catch_file, sheet = .x)) %>%
  mutate(
    site = clean_names_text(site),
    species = clean_names_text(species),
    date = as.Date(date)
  )

metadata_clean <- read_csv(
  here::here("data", "workshop2", "estuary_metadata.csv"),
  show_col_types = FALSE
) %>%
  mutate(site_name = clean_names_text(site_name))

dictionary_clean <- read_csv(
  here::here("data", "workshop2", "species_dictionary.csv"),
  show_col_types = FALSE
) %>%
  mutate(common_name = clean_names_text(common_name))

sonde_clean <- read_csv(
  here::here("data", "workshop2", "estuary_sonde_data.csv"),
  show_col_types = FALSE
) %>%
  mutate(
    site = clean_names_text(site),
    timestamp = dmy_hm(timestamp, tz = "Australia/Brisbane"),
    date = as.Date(timestamp, tz = "Australia/Brisbane"),
    turbidity = na_if(turbidity, -999)
  )

# Preserve NA if an entire group has no valid readings
mean_valid <- function(x) {
  if (all(is.na(x))) NA_real_ else mean(x, na.rm = TRUE)
}

daily_water <- sonde_clean %>%
  group_by(site, date) %>%
  summarise(
    temperature = mean_valid(temperature),
    salinity = mean_valid(salinity),
    turbidity = mean_valid(turbidity),
    .groups = "drop"
  )

catch_complete <- catch_clean %>%
  complete(
    nesting(site, date),
    species = dictionary_clean$common_name
  ) %>%
  mutate(count = coalesce(count, 0))

master_data <- catch_complete %>%
  left_join(
    dictionary_clean,
    by = join_by(species == common_name),
    relationship = "many-to-one"
  ) %>%
  left_join(
    metadata_clean,
    by = join_by(site == site_name),
    relationship = "many-to-one"
  ) %>%
  left_join(
    daily_water,
    by = join_by(site, date),
    relationship = "many-to-one"
  ) %>%
  mutate(
    zone = factor(
      zone,
      levels = c("Upstream", "Middle", "Downstream", "Marine")
    )
  ) %>%
  select(
    site, date, zone, lat, lon,
    scientific_name, count,
    temperature, salinity, turbidity
  ) %>%
  arrange(zone, date, scientific_name)

# Validate the finished dataset
stopifnot(
  nrow(master_data) == 480,
  !anyNA(master_data$scientific_name),
  !anyNA(master_data$zone),
  !anyNA(master_data$salinity),
  !anyDuplicated(
    master_data[c("site", "date", "scientific_name")]
  )
)

glimpse(master_data)
## Rows: 480
## Columns: 10
## $ site            <chr> "upper_ross", "upper_ross", "upper_ross", "upper_ross"…
## $ date            <date> 2026-05-01, 2026-05-01, 2026-05-01, 2026-05-01, 2026-…
## $ zone            <fct> Upstream, Upstream, Upstream, Upstream, Upstream, Upst…
## $ lat             <dbl> -19.31, -19.31, -19.31, -19.31, -19.31, -19.31, -19.31…
## $ lon             <dbl> 146.74, 146.74, 146.74, 146.74, 146.74, 146.74, 146.74…
## $ scientific_name <chr> "Acanthopagrus spp.", "Lates calcarifer", "Lutjanus ar…
## $ count           <dbl> 2, 5, 0, 6, 2, 8, 1, 4, 2, 4, 0, 0, 2, 5, 3, 0, 2, 6, …
## $ temperature     <dbl> 24.05739, 24.05739, 24.05739, 24.05739, 23.92100, 23.9…
## $ salinity        <dbl> 4.883629, 4.883629, 4.883629, 4.883629, 4.907339, 4.90…
## $ turbidity       <dbl> 24.67218, 24.67218, 24.67218, 24.67218, 25.10221, 25.1…
summary_table <- master_data %>%
  group_by(scientific_name, zone) %>%
  summarise(
    n_catch = sum(!is.na(count)),
    mean_count = mean(count, na.rm = TRUE),
    sd_count = sd(count, na.rm = TRUE),
    n_salinity = sum(!is.na(salinity)),
    mean_salinity = mean(salinity, na.rm = TRUE),
    sd_salinity = sd(salinity, na.rm = TRUE),
    .groups = "drop"
  ) %>%
  mutate(
    se_count = sd_count / sqrt(n_catch),
    se_salinity = sd_salinity / sqrt(n_salinity)
  ) %>%
  arrange(scientific_name, zone)

summary_table
## # A tibble: 16 × 10
##    scientific_name    zone  n_catch mean_count sd_count n_salinity mean_salinity
##    <chr>              <fct>   <int>      <dbl>    <dbl>      <int>         <dbl>
##  1 Acanthopagrus spp. Upst…      30       2.57    1.65          30          4.95
##  2 Acanthopagrus spp. Midd…      30       2.23    1.57          30         14.9 
##  3 Acanthopagrus spp. Down…      30       2       1.51          30         28.0 
##  4 Acanthopagrus spp. Mari…      30       2.33    1.88          30         34.0 
##  5 Lates calcarifer   Upst…      30       4.8     1.69          30          4.95
##  6 Lates calcarifer   Midd…      30       2.2     1.32          30         14.9 
##  7 Lates calcarifer   Down…      30       1.6     1.40          30         28.0 
##  8 Lates calcarifer   Mari…      30       1.57    1.36          30         34.0 
##  9 Lutjanus argentim… Upst…      30       1.9     1.16          30          4.95
## 10 Lutjanus argentim… Midd…      30       1.97    1.13          30         14.9 
## 11 Lutjanus argentim… Down…      30       2       1.64          30         28.0 
## 12 Lutjanus argentim… Mari…      30       1.5     1.14          30         34.0 
## 13 Platycephalus spp. Upst…      30       2.3     1.82          30          4.95
## 14 Platycephalus spp. Midd…      30       1.97    1.45          30         14.9 
## 15 Platycephalus spp. Down…      30       2.1     0.960         30         28.0 
## 16 Platycephalus spp. Mari…      30       5.67    1.30          30         34.0 
## # ℹ 3 more variables: sd_salinity <dbl>, se_count <dbl>, se_salinity <dbl>
estuary_plot <- ggplot(
  summary_table,
  aes(
    x = mean_salinity,
    y = mean_count,
    colour = zone
  )
) +
  geom_errorbar(
    aes(
      ymin = mean_count - se_count,
      ymax = mean_count + se_count
    ),
    width = 0.3
  ) +
  geom_point(size = 3) +
  facet_wrap(~ scientific_name, ncol = 2) +
  scale_colour_viridis_d(drop = FALSE) +
  labs(
    x = "Mean daily salinity",
    y = "Mean daily fish count",
    colour = "Estuary zone",
    caption = paste(
      "Points represent zone means across 30 sampled days.",
      "Error bars show ±1 standard error of fish counts."
    )
  ) +
  theme_minimal() +
  theme(
    strip.text = element_text(face = "italic"),
    legend.position = "bottom"
  )

estuary_plot

dir.create(
  here::here("outputs"),
  recursive = TRUE,
  showWarnings = FALSE
)

write_csv(
  master_data,
  here::here("outputs", "estuary_master_data.csv")
)

write_csv(
  summary_table,
  here::here("outputs", "estuary_summary_table.csv")
)

ggsave(
  here::here("outputs", "estuary_salinity_fish_counts.png"),
  plot = estuary_plot,
  width = 9,
  height = 6,
  dpi = 300
)