# Load necessary library
library(ncdf4)

# Define input parameters
dates <- format(seq(as.Date("20190930", "%Y%m%d"), as.Date("20240930", "%Y%m%d"), 7), "%Y%m%d")
var_obs <- "prlr"
locations <- list(
  	dcoop_jardinete = c(lat = 39.25, lon = 356.93),
  	dcoop_rebollo = c(lat = 39.25, lon = 356.97),
  	dcoop_fherminia = c(lat = 39.35, lon = 356.93),
  	dcoop_migueleta = c(lat = 39.38, lon = 356.92),
  	dcoop_manzaneque = c(lat = 39.43, lon = 356.88),
  	dcoop_pozo = c(lat = 39.5, lon = 3.13),
  	dcoop_s57zr = c(lat = 39.55, lon = 3.12),
   	dcoop_mjose = c(lat = 39.6, lon = 3.12),
        mcodax_cambados_orosal = c(lat = 41.9, lon = 351.18),
  	mcodax_cambados_pontevedra = c(lat = 42.45, lon = 351.3), 
  	mcodax_cambados_vgarousa = c(lat = 42.48, lon = 351.3),
  	mcodax_meano_vgarousa = c(lat = 42.50, lon = 351.3) ,
  	mcodax_meano_pontevedra = c(lat = 42.50, lon = 351.3), 
  	mcodax_ribadumia_vgarousa = c(lat = 42.51, lon = 351.3), 
  	mcodax_sanxenxo_vgarousa = c(lat = 42.53, lon = 351.3), 
  	mcodax_vgarousa_vgarousa = c(lat = 42.53, lon = 351.35), 
  	mcodax_vnarousa_vgarousa = c(lat = 42.53, lon = 351.3), 
  	mcodax_vlardevos = c(lat = 42.56, lon = 352.63),
  
    matarromera_sanroman = c(lat = 41.64, lon = 355.68),
   matarromera_lasmarcas = c(lat = 41.36, lon = 355.24),
   vriotajo = c(lat = 39.87, lon = 355.87)
)

location_names <- names(locations)  # Extract names for reference
patho <- "/esarchive/recon/ecmwf/era5land/weekly_mean/"

# Initialize results array
results_array <- array(NA, dim = c(length(locations), length(dates), 1),
                       dimnames = list(loc = location_names, dates = dates, variable = var_obs))

# Function to find the nearest index in the NetCDF grid
find_nearest_index <- function(value, grid) {
  return(which.min(abs(grid - value)))
}

# Loop through dates
for (j in seq_along(dates)) {
  date <- dates[j]
  path_obs <- paste0(patho, "prlr_f1h/prlr_", date, ".nc")
  cat("Processing date:", date, "\n")  # Print progress
  
  # Open netCDF file
  nc_data <- nc_open(path_obs)
  
  # Extract latitude, longitude, and variable data
  lat_vals <- ncvar_get(nc_data, "lat")  # Use "lat" instead of "latitude"
  lon_vals <- ncvar_get(nc_data, "lon")  # Use "lon" instead of "longitude"
  time_vals <- ncvar_get(nc_data, "time")  # Extract time variable
  tas_vals <- ncvar_get(nc_data, var_obs)  # Get the temperature variable
  #cat("tas_vals dimensions:", dim(tas_vals), "\n")
  
  # Extract fill value for handling missing data
  fill_value <- ncatt_get(nc_data, var_obs, "_FillValue")$value
  
  # Close the NetCDF file after extracting data
  nc_close(nc_data)
  
  # Process each location
  for (i in seq_along(locations)) {
    loc_name <- location_names[i]
    loc <- locations[[i]]
    lat_val <- loc["lat"]
    lon_val <- loc["lon"]
    #cat("Processing location:", loc_name, "\n")
    
    # Find the closest lat/lon index from the NetCDF data
    lat_idx <- find_nearest_index(lat_val, lat_vals)
    lon_idx <- find_nearest_index(lon_val, lon_vals)
    
    # Extract the temperature value at the closest lat/lon index
    obs_loc <- tas_vals[lon_idx, lat_idx]  # Adjusting for (lon, lat, time) order
    
    # Replace missing values with NA
    obs_loc[obs_loc == fill_value] <- NA
    
    # If precipitation, convert to mm day 
    if (var_obs == "prlr") {
    obs_loc <- obs_loc*86400000}

    # Store the result in the results array
    results_array[i, j, 1] <- mean(obs_loc, na.rm = TRUE)  # Mean value over time (if 3D)
    
  }
}

# Convert results array to a data frame
results_df <- as.data.frame(results_array)
results_df <- cbind(loc = rownames(results_df), results_df)  # Add location names
colnames(results_df) <- c("loc", dates)

# Print final data frame
print(results_df)

# Transpose data frame for better readability
transposed_df <- as.data.frame(t(results_df[-1]))  # Exclude first column ("loc")
colnames(transposed_df) <- results_df$loc  # Use location names as headers
transposed_df <- cbind(dates = rownames(transposed_df), transposed_df)
transposed_df[-1] <- lapply(transposed_df[-1], function(x) round(as.numeric(x), 2))

# Save to CSV
write.csv(transposed_df, file = "/esarchive/scratch/ptrascas/R/bigpredidata_ceigram/reanalysis_for_calibration/subseasonal_prlr.csv", row.names = FALSE)

cat("Data successfully saved to CSV.\n")
  
