library(startR)
library(ggplot2)
library(reshape2)

# Define location
target_lat <- 39.87
target_lon <- 355.87

# Variables and forecast configuration
fcst.sdate <- "20240826"  # Last Monday of August
ltmin <- 1
ltmax <- 35
fcst.nmember <- 16
base_temp <- 10  # Base temperature for GDD

# Output path
output_dir <- "/esarchive/scratch/ptrascas/R/dev-test_bigpredidata/sunset/sunset/"
if (!dir.exists(output_dir)) dir.create(output_dir, recursive = TRUE)

# Forecast paths
fcst_path_tasmax <- "/esarchive/exp/ncep/cfs-v2/daily/s2s/tasmax/tasmax_$file_date$.nc"
fcst_path_tasmin <- "/esarchive/exp/ncep/cfs-v2/daily/s2s/tasmin/tasmin_$file_date$.nc"

# File date dimension
file_dates.fcst <- fcst.sdate
dim(file_dates.fcst) <- c(1)

# Load tasmax
fcst_tasmax <- Start(
  dat = fcst_path_tasmax,
  var = "tasmax",
  file_date = file_dates.fcst,
  time = indices(ltmin:ltmax),
  latitude = values(target_lat),
  longitude = values(target_lon),
  ensemble = indices(1:fcst.nmember),
  retrieve = TRUE
)

# Load tasmin
fcst_tasmin <- Start(
  dat = fcst_path_tasmin,
  var = "tasmin",
  file_date = file_dates.fcst,
  time = indices(ltmin:ltmax),
  latitude = values(target_lat),
  longitude = values(target_lon),
  ensemble = indices(1:fcst.nmember),
  retrieve = TRUE
)

# Extract data
tasmax_data <- fcst_tasmax[1, 1, 1, , 1, 1, ]
tasmin_data <- fcst_tasmin[1, 1, 1, , 1, 1, ]

# Check data presence
if (!is.null(tasmax_data) & !is.null(tasmin_data)) {
  message("✅ Both tasmax and tasmin data loaded successfully.")
  
  n_members <- dim(tasmax_data)[2]
  n_days <- dim(tasmax_data)[1]
  date_seq <- seq(as.Date(fcst.sdate, "%Y%m%d"), by = "1 day", length.out = n_days)
  
  # Convert to Celsius
  tasmax_c <- tasmax_data - 273.15
  tasmin_c <- tasmin_data - 273.15
  
  # Compute daily GDD
  gdd_data <- ((tasmax_c + tasmin_c) / 2) - base_temp
  gdd_data[gdd_data < 0] <- 0
  
  # Accumulate daily GDD
  gdd_cumulative <- matrix(0, nrow = n_days, ncol = n_members)
  for (i in 1:n_members) {
    gdd_cumulative[, i] <- cumsum(gdd_data[, i])
  }
  
  # Build data frame for cumulative GDD
  df_gdd <- data.frame(
    Date = rep(date_seq, each = n_members),
    Ensemble = factor(rep(1:n_members, times = n_days)),
    GDD = as.vector(t(gdd_cumulative))
  )
  
  # Save plot
  output_path <- file.path(output_dir, "GDD_cumulative_forecast.png")
  
  if (nrow(df_gdd) > 0) {
    message("📈 Creating cumulative GDD plot...")
    
    png(filename = output_path, width = 1200, height = 600, res = 150)
    print(
      ggplot(df_gdd, aes(x = Date, y = GDD, color = Ensemble)) +
        geom_line(size = 1.2) +
        labs(
          title = "Cumulative GDD Forecast - Ensemble Members",
          x = "Date",
          y = "Cumulative GDD (°C·day)",
          color = "Ensemble Member"
        ) +
        theme_minimal(base_size = 14) +
        theme(axis.text.x = element_text(angle = 45, hjust = 1))
    )
    dev.off()
    message("✅ Cumulative GDD plot saved at: ", output_path)
  } else {
    warning("⚠️ df_gdd is empty — plot skipped.")
  }
  
} else {
  stop("❌ Missing tasmax or tasmin data.")
}

