# Load libraries once at the top
library(tidyverse)
library(readxl)
library(beepr)
library(reshape2)
library(gganimate)
library(patchwork)
library(dplyr)
library(scales)
library(magick)
#library(av)

# Set working directory to script location
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))

# List of Scenario names
# Scenario_names <- c("Fig2_Scenario1_f0w2", "Fig2_Scenario1_f1w2","Fig2_Scenario1_f2w2", "Fig2_Scenario1_f3w2","Fig2_Scenario1_f4w2",
#                     "Fig2_Scenario1_f2w0", "Fig2_Scenario1_f2w1","Fig2_Scenario1_f2w3","Fig2_Scenario1_f2w4",
#                     "Fig2_Scenario2_f0w2", "Fig2_Scenario2_f1w2","Fig2_Scenario2_f2w2", "Fig2_Scenario2_f3w2","Fig2_Scenario2_f4w2",
#                     "Fig2_Scenario2_f2w0", "Fig2_Scenario2_f2w1","Fig2_Scenario2_f2w3","Fig2_Scenario2_f2w4")

Scenario_names <- c("Fig3_A", "Fig3_B", "Fig3_C", "Fig3_D",
                    "Fig3_E", "Fig3_F", "Fig3_G","Fig4_A",
                    "Fig4_B", "Fig4_C","Fig4_D","Fig4_E",
                    "Fig4_F", "Fig4_G", "Fig6_A", "Fig6_B",
                    "Fig6_C")
resplot = T 


for (Scenario_name in Scenario_names) {
  cat("\nRunning Scenario:", Scenario_name, "\n")
  
  assign("Scenario_name", Scenario_name, envir = .GlobalEnv)
  
  # Load landscape
  H_loaded <- read_excel(paste0("Landscape_Scenarios/", Scenario_name, ".xlsx"), col_names = FALSE)
  
  # Run model pipeline
  source("Parameters.R")         # Parameters
  source("Functions.R")          # Functions
  source("Initialisation.R")     # Initialisation
  
  year <- 2
  Update_dispersal <- c(1:210)
  plotyears = c(2)
  
  # Run the spatial model
  system.time(source("SpatialModel_Hanna.R"))
  
  saveRDS(NewData, paste0("Data/", Scenario_name, ".RDS"))
  
  # # Save RDS interactively
  # saveRDSAsk <- function(object, file = "") {
  #   write = 'y'
  #   if (file.exists(file)) {
  #     message = paste('The file', file, 'already exists. Overwrite? [y/n]: ')
  #     write <- readline(prompt = message)
  #   }
  #   if (write == 'y') {
  #     saveRDS(object, file)
  #   } else {
  #     print("The object has not been saved!")
  #   }
  # }
  # saveRDSAsk(NewData, paste0("Data/", Scenario_name, ".RDS"))
  
  # Run the animation script
 system.time(source("Animation.R"))
  
  #beep(sound = 5)
  
  cat("Finished:", Scenario_name, "\n")
}
