library(CSTools)
library(startR)
library(ggplot2)
library(lubridate)

# Load necessary library
library(ncdf4)

# Define input parameters

dates <- format(seq(as.Date("20230101", "%Y%m%d"), as.Date("20231031", "%Y%m%d"), 7), "%Y%m%d")
variable<-"tasmax"
# Extract location viñedos del rio Tajo as an example
lat = 39.87
lon = 355.87

obs.grid <- "-r1440x721cds" 

switch (tolower(variable),
        "tas"     = {freq.hcst <- 'f24h';   freq.obs <- 'f1h'},
        "tasmin"  = {freq.hcst <- 'f24h';   freq.obs <- 'f24h'},
        "tasmax"  = {freq.hcst <- 'f24h';   freq.obs <- 'f24h'},
        "psl"     = {freq.hcst <- 'f24h';   freq.obs <- 'f1h'},
        "prlr"    = {freq.hcst <- 'f6h';  freq.obs <- 'f1h'; accum <- TRUE},
        "rsds"    = {freq.hcst <- 's0-24h'; freq.obs <- 'f1h'; accum <- TRUE},
        "sfcwind" = {freq.hcst <- 'f24h';   freq.obs <- 'f1h'}
)

#location_names <- names(locations)  # Extract names for reference
fcst.freq <- "weekly_mean"
obs.dir  <- "/esarchive/recon/ecmwf/era5land/"
obs.path  <- paste0(
  obs.dir,fcst.freq,"/$var$_",
  freq.obs,"/$var$_$time$.nc")


obs_tasmax <- Start(dat = obs.path,
             var = variable,
             time = dates,
             latitude = values(lat),
             longitude = values(lon),
             synonims = list(latitude=c('lat','latitude'),
                             longitude=c('lon','longitude')),
             split_multiselected_dims = TRUE,
             retrieve = TRUE)


# change the unit of temperature from °C to K

obs_tasmax <- obs_tasmax - 273.15

variable<-"tasmin"
obs_tasmin <- Start(dat = obs.path,
                    var = variable,
                    time = dates,
                    latitude = values(lat),
                    longitude = values(lon),
                    synonims = list(latitude=c('lat','latitude'),
                                    longitude=c('lon','longitude')),
                    split_multiselected_dims = TRUE,
                    retrieve = TRUE)


# change the unit of temperature from °C to K

obs_tasmin <- obs_tasmin - 273.15


# Set base temperature
base_temp <- 10

# Compute daily excess above 10°C
gdd <- (obs_tasmin + obs_tasmax) / 2 - base_temp

# Set values below 0 to 0 (i.e., no accumulation if below base)
gdd[gdd < 0] <- 0

# Accumulate over time (assume time is the 3rd dimension)
gdd <- apply(gdd, MARGIN = c(1, 2, 4, 5), FUN = cumsum)

# If you're using CSTools format, you can put it into a CSTools-like object again:
gdd_cst <- obs
gdd_cst$data <- gdd

# Flatten time series
gdd_series <- as.numeric(gdd_cst$data)

# Rebuild date axis from your original list of dates
dates <- as.Date(format(seq(as.Date("20230101", "%Y%m%d"), 
                            as.Date("20231031", "%Y%m%d"), 7), "%Y%m%d"), "%Y%m%d")

# Create dataframe
df_gdd <- data.frame(
  Date = dates,
  GDD = gdd_series[1:length(dates)]
)

library(ggplot2)

# Define output path (make sure folder exists and is writable)
output_path <- "gdd_timeseries.png"  # or e.g. "/home/youruser/plots/gdd_timeseries.png"

# Optional: check current working directory
# getwd()

# Open PNG device
# Assuming df_gdd is your data frame with 'Date' and 'GDD' columns
library(ggplot2)
library(scales)

# Assuming df_gdd is your data frame with 'Date' and 'GDD' columns
png(filename = output_path, width = 1200, height = 600, res = 150)

# Create the plot with two rows of x-axis labels
p <- ggplot(df_gdd, aes(x = Date, y = GDD)) +
  geom_line(color = "#1b9e77", size = 1) +
  geom_point(color = "#1b9e77", size = 1) +
  
  # Set up the main x-axis scale for month names, only once per month
  scale_x_date(date_breaks = "1 month", date_labels = "%b") +  # Month name on the main axis
  
  # Adding the day labels manually using geom_text() (for each date point)
  geom_text(aes(x = Date, y = rep(min(df_gdd$GDD) - 2, length(Date)), 
                label = format(Date, "%d")), 
            size = 3, angle = 0, vjust = 1.5) +  # Above the x-axis
  
  labs(title = "Accumulated Growing Degree Days (GDD)",
       subtitle = "Threshold base: 10°C | Location: Viñedos del Río Tajo",
       x = "Week Start",
       y = "Accumulated GDD (°C)") +
  theme_minimal(base_size = 14) +
  
  # Theme adjustments for label positioning
  theme(axis.text.x = element_text(angle = 0, hjust = 0.5, size = 12),
        plot.title = element_text(face = "bold"),
        plot.subtitle = element_text(color = "gray40"),
        axis.title.x = element_blank(),  # Removing default x-axis label
        axis.title.y = element_text(size = 14))

# Render the plot to PNG
print(p)

