# ============================================================================
# BATCH PIPELINE RUNNER: Scripts 40, 80, 90 for Multiple Dates
# ============================================================================
# Purpose: Run weekly reporting pipeline for multiple dates (Jan 21, 2026 - Feb 18, 2026)
# Project: aura
# ============================================================================

suppressPackageStartupMessages({
  library(lubridate)
  library(rmarkdown)
})

# Configuration
PROJECT <- "aura"
START_DATE <- as.Date("2026-01-26")
END_DATE <- as.Date("2026-02-23")
OFFSET <- 7

# Generate date sequence (every 7 days)
date_sequence <- seq(START_DATE, END_DATE, by = "7 days")

cat("\n========================================================\n")
cat("BATCH PIPELINE RUNNER for AURA Project\n")
cat("========================================================\n")
cat(sprintf("Project: %s\n", PROJECT))
cat(sprintf("Date range: %s to %s\n", format(START_DATE), format(END_DATE)))
cat(sprintf("Interval: Every %d days\n", OFFSET))
cat(sprintf("Total dates to process: %d\n", length(date_sequence)))
cat(sprintf("Dates: %s\n", paste(format(date_sequence), collapse = ", ")))
cat("========================================================\n\n")

# Process each date
for (i in seq_along(date_sequence)) {
  current_date <- date_sequence[i]
  date_str <- format(current_date, "%Y-%m-%d")
  
  cat("\n")
  cat(strrep("=", 70), "\n")
  cat(sprintf("PROCESSING DATE: %s (%d of %d)\n", date_str, i, length(date_sequence)))
  cat(strrep("=", 70), "\n\n")
  
  # ==== SCRIPT 40: Create Weekly Mosaic ====
 # cat(sprintf("[%s] Running Script 40: Weekly Mosaic Creation\n", Sys.time()))
 # tryCatch({
  #  r_path <- "C:\\Program Files\\R\\R-4.4.3\\bin\\x64\\Rscript.exe"
  #  script_40 <- "r_app/40_mosaic_creation_per_field.R"
  #  cmd_40 <- c(script_40, date_str, as.character(OFFSET), PROJECT)
  #  
  #  result_40 <- system2(r_path, args = cmd_40)
  #  
  #  if (result_40 == 0) {
  #    cat(sprintf("[%s] ✓ Script 40 completed successfully\n\n", Sys.time()))
  #  } else {
  #    cat(sprintf("[%s] ✗ Script 40 failed with exit code %d (continuing anyway)\n\n", Sys.time(), result_40))
 #   }
 # }, error = function(e) {
 #   cat(sprintf("[ERROR] Script 40 error: %s (continuing anyway)\n\n", e$message))
 # })
  
  # ==== SCRIPT 80: Calculate KPIs ====
  cat(sprintf("[%s] Running Script 80: Calculate KPIs\n", Sys.time()))
  tryCatch({
    r_path <- "C:\\Program Files\\R\\R-4.4.3\\bin\\x64\\Rscript.exe"
    script_80 <- "r_app/80_calculate_kpis.R"
    # Note: R80 argument order is [END_DATE] [PROJECT] [OFFSET]
    cmd_80 <- c(script_80, date_str, PROJECT, as.character(OFFSET))
    
    result_80 <- system2(r_path, args = cmd_80)
    
    if (result_80 == 0) {
      cat(sprintf("[%s] ✓ Script 80 completed successfully\n\n", Sys.time()))
    } else {
      cat(sprintf("[%s] ✗ Script 80 failed with exit code %d (continuing anyway)\n\n", Sys.time(), result_80))
    }
  }, error = function(e) {
    cat(sprintf("[ERROR] Script 80 error: %s (continuing anyway)\n\n", e$message))
  })
  
  # ==== SCRIPT 90: Generate Report ====
#  cat(sprintf("[%s] Running Script 90: Generate Agronomic Support Report\n", Sys.time()))
  #tryCatch({
    #output_filename <- sprintf("SmartCane_Report_agronomic_support_%s_%s.docx", PROJECT, date_str)
 #   
 #   render(
 #     "r_app/90_CI_report_with_kpis_agronomic_support.Rmd",
 #     params = list(data_dir = PROJECT, report_date = as.Date(date_str)),
 #     output_file = output_filename,
 #     output_dir = file.path("laravel_app/storage/app", PROJECT, "reports"),
 #     quiet = FALSE
 #   )
 #   
#    cat(sprintf("[%s] ✓ Script 90 completed successfully\n", Sys.time()))
#    cat(sprintf("    Output: laravel_app/storage/app/%s/reports/%s\n\n", PROJECT, output_filename))
#  }, error = function(e) {
#    cat(sprintf("[%s] ✗ Script 90 failed: %s (continuing anyway)\n\n", Sys.time(), e$message))
#  })
}

# Summary
cat("\n")
cat(strrep("=", 70), "\n")
cat("BATCH PROCESSING COMPLETE\n")
cat(strrep("=", 70), "\n")
cat(sprintf("Processed %d dates from %s to %s\n", 
            length(date_sequence), 
            format(START_DATE), 
            format(END_DATE)))
cat("Check output directory for generated reports\n")
cat(sprintf("Reports location: laravel_app/storage/app/%s/reports/\n", PROJECT))
cat(strrep("=", 70), "\n\n")