#!/bin/bash
# This script searches through the VIIRS Tandem composite image repository to identify
# all possible triplet combinations to process for winds. It's based on a series of
# selection rules and will form the "best" configuration for Tandem processing from the
# current available imagery. There are three possible Tandem configurations: Three-Sat,
# Dual-Sat, or Single-Sat processing. The file listing is processed separately for possible 
# triplet combinations for each pole. 
#
# The linked images in the Tandem composite image repository have all been renamed to NOAA20
# to simplify handling the winds processing within the algorithm. However, this script makes use
# of the linked filenames to identify the source of each file - NPP, NOAA20, or NOAA21 - in order
# to apply the selection rules. 

#       The list looks something like this:
#       "../j02_maps/nps_NOAA21_VIIRS_750M_Granule_3305x3305_2025230_0922_38.nc"
#       "../npp_maps/nps_NPP_VIIRS_750M_Granule_3305x3305_2025230_0949_41.nc"
#       "../j01_maps/nps_NOAA20_VIIRS_750M_Granule_3305x3305_2025230_1012_26.nc"
#       "../j02_maps/nps_NOAA21_VIIRS_750M_Granule_3305x3305_2025230_1105_04.nc"
#       "../npp_maps/nps_NPP_VIIRS_750M_Granule_3305x3305_2025230_1130_40.nc"
#       "../j01_maps/nps_NOAA20_VIIRS_750M_Granule_3305x3305_2025230_1153_56.nc"
#       "../j02_maps/nps_NOAA21_VIIRS_750M_Granule_3305x3305_2025230_1246_04.nc"
#
# The selection rules are as follows:
#
# 1) If the middle image of the triplet is from NPP, there are two possible configurations for the triplet.
#    Three-Sat Tandem:	Triplet comprised of images from all three satellites with a time step of roughly 25 minutes.
#    Single-Sat:	If Three-Sat not possible, all three triplet images come from NPP with a time step of roughly 
#                       101 minutes.
#
# 2) If the middle image of the triplet is from NOAA20, there are two possible configurations for the triplet. 
#    Dual-Sat Tandem:	Triplet comprised of the first and third images from NOAA21 but only if the time step is
#                       roughly 50 minutes.
#    Single-Sat:	If Dual-Sat not possible, all three triplet images come from NOAA20 with a time step of 
#                       roughly 101 minutes.
#
# 3) If the middle image of the triplet is from NOAA21, there are two possible configurations for the triplet.
#    Dual-Sat Tandem:	Triplet comprised of the first and third images from NOAA20 but only if the time step is
#                       roughly 50 minutes.
#    Single-Sat:	If Dual-Sat not possible, all three triplet images come from NOAA21 with a time step of 
#                       roughly 101 minutes.
      
# For all three cases above, if neither configuration is possible, processing moves to the next file in the list until all 
# current files in the tandem composite image repository have been processed.
# 
#  aab 8-21-2025

# Set the directory to the Tandem Composite Image repository
directory="./Temporary_Data/Tandem_maps"

# Initialize arrays for the two separate lists
nps_files=()
sps_files=()

# Use the symbolic links in the Tandem Image Composites directory to sort them into arrays
while IFS= read -r link; do
  target_file=$(readlink "$link")
  if [[ "$target_file" == *nps* ]]; then
    nps_files+=("$target_file")
  elif [[ "$target_file" == *sps* ]]; then
    sps_files+=("$target_file")
  fi
done < <(find "$directory" -maxdepth 1 -type l -name "*.nc" | sort)

echo ' '
echo 'List out current files we are working with...'
echo "NPS Files:"
printf '%s\n' "${nps_files[@]}"

echo ' '
echo "SPS Files:"
printf '%s\n' "${sps_files[@]}"
echo ' '

# Function to get the satellite name from a filename
get_satellite() {
  local filename=$(basename "$1")
  if [[ "$filename" == *NOAA20* ]]; then
    echo "j01"
  elif [[ "$filename" == *NOAA21* ]]; then
    echo "j02"
  elif [[ "$filename" == *NPP* ]]; then
    echo "npp"
  fi
}

# Function to get the timestamp in minutes since epoch
get_timestamp_minutes() {
  local filename=$(basename "$1")
  local date_time_parts=$(echo "$filename" | rev | cut -d'_' -f2,3 | rev)
  local year_day=${date_time_parts%_*}
  local time=${date_time_parts#*_}

  local year=${year_day:0:4}
  local day_of_year=${year_day:4:3}
  local hour=${time:0:2}
  local minute=${time:2:2}

  local start_of_year_ts_sec=$(date -d "${year}-01-01" +%s)
  local days_sec=$(( (10#$day_of_year - 1) * 24 * 60 * 60 ))
  local hours_sec=$(( 10#$hour * 60 * 60 ))
  local minutes_sec=$(( 10#$minute * 60 ))

  echo $(( (start_of_year_ts_sec + days_sec + hours_sec + minutes_sec) / 60 ))
}

# Function to find and print triplets based on the rules below
process_triplets() {
  local -n files_ref=$1
  local title=$2
  
  echo "---"
  echo "### $title"
  echo "---"

  if [ ${#files_ref[@]} -lt 3 ]; then
    echo "Not enough files to form triplets in this set."
    return
  fi

  # Step through the list and use each file to attempt to build a valid triplet
  for (( middle_idx=0; middle_idx<${#files_ref[@]}; middle_idx++ )); do
    file2=${files_ref[$middle_idx]}
    sat2=$(get_satellite "$file2")
    ts2=$(get_timestamp_minutes "$file2")

    # Look backwards in the list for the first file of the triplet
    for (( first_idx=middle_idx-1; first_idx>=0; first_idx-- )); do
      file1=${files_ref[$first_idx]}
      sat1=$(get_satellite "$file1")
      ts1=$(get_timestamp_minutes "$file1")
      diff1_2=$(( ts2 - ts1 ))

      # Look forwards in the list for the third file of the triplet
      for (( third_idx=middle_idx+1; third_idx<${#files_ref[@]}; third_idx++ )); do
        file3=${files_ref[$third_idx]}
        sat3=$(get_satellite "$file3")
        ts3=$(get_timestamp_minutes "$file3")
        diff2_3=$(( ts3 - ts2 ))

        # Apply triplet rules based on the middle/target image (file2) and check time diffs
        case "$sat2" in
          npp)
            # Rule 1: All three satellites, roughly 20-30 mins apart
            if [[ ($sat1 == "j01" || $sat1 == "j02") && ($sat3 == "j01" || $sat3 == "j02") && $diff1_2 -ge 20 && $diff1_2 -le 30 && $diff2_3 -ge 20 && $diff2_3 -le 30 ]]; then
              echo "Found Triplet (npp Target Image, Three-Sat Tandem Configuration)"
              echo "  - File 1: $file1"
              echo "  - File 2: $file2"
              echo "  - File 3: $file3"
              echo "  - Time diffs: $diff1_2 min, $diff2_3 min"
              echo "---"
              continue 3
            # Rule 2: First and third are j01, roughly 45-60 mins apart
            elif [[ $sat1 == "j01" && $sat3 == "j01" && $diff1_2 -ge 45 && $diff1_2 -le 60 && $diff2_3 -ge 45 && $diff2_3 -le 60 ]]; then
              echo "Found Triplet (npp Target Image, Dual-Sat Tandem Configuration with j01)"
              echo "  - File 1: $file1"
              echo "  - File 2: $file2"
              echo "  - File 3: $file3"
              echo "  - Time diffs: $diff1_2 min, $diff2_3 min"
              echo "---"
              continue 3
            # Rule 3: All three npp, roughly 90-110 mins apart
            elif [[ $sat1 == "npp" && $sat3 == "npp" && $diff1_2 -ge 90 && $diff1_2 -le 110 && $diff2_3 -ge 90 && $diff2_3 -le 110 ]]; then
              echo "Found Triplet (npp Target Image, Single-Sat Configuration with npp)"
              echo "  - File 1: $file1"
              echo "  - File 2: $file2"
              echo "  - File 3: $file3"
              echo "  - Time diffs: $diff1_2 min, $diff2_3 min"
              echo "---"
              continue 3
            fi
            ;;

          j01)
            # Rule 1: First and third from j02, roughly 45-60 mins apart
            if [[ $sat1 == "j02" && $sat3 == "j02" && $diff1_2 -ge 45 && $diff1_2 -le 60 && $diff2_3 -ge 45 && $diff2_3 -le 60 ]]; then
              echo "Found Triplet (j01 Target Image, Dual-Sat Tandem configuration with j02)"
              echo "  - File 1: $file1"
              echo "  - File 2: $file2"
              echo "  - File 3: $file3"
              echo "  - Time diffs: $diff1_2 min, $diff2_3 min"
              echo "---"
              continue 3
            # Rule 2: All three j01, roughly 90-110 mins apart
            elif [[ $sat1 == "j01" && $sat3 == "j01" && $diff1_2 -ge 90 && $diff1_2 -le 110 && $diff2_3 -ge 90 && $diff2_3 -le 110 ]]; then
              echo "Found Triplet (j01 Target Image, Single-Sat configuration with j01)"
              echo "  - File 1: $file1"
              echo "  - File 2: $file2"
              echo "  - File 3: $file3"
              echo "  - Time diffs: $diff1_2 min, $diff2_3 min"
              echo "---"
              continue 3
            fi
            ;;

          j02)
            # Rule 1: First and third from j01, roughly 45-60 mins apart
            if [[ $sat1 == "j01" && $sat3 == "j01" && $diff1_2 -ge 45 && $diff1_2 -le 60 && $diff2_3 -ge 45 && $diff2_3 -le 60 ]]; then
              echo "Found Triplet (j02 Target Image, Dual-Sat Tandem Configuration with j01)"
              echo "  - File 1: $file1"
              echo "  - File 2: $file2"
              echo "  - File 3: $file3"
              echo "  - Time diffs: $diff1_2 min, $diff2_3 min"
              echo "---"
              continue 3
            # Rule 2: All three j02, roughly 90-110 mins apart
            elif [[ $sat1 == "j02" && $sat3 == "j02" && $diff1_2 -ge 90 && $diff1_2 -le 110 && $diff2_3 -ge 90 && $diff2_3 -le 110 ]]; then
              echo "Found Triplet (j02 Target Image, Single-Sat configuration with j02)"
              echo "  - File 1: $file1"
              echo "  - File 2: $file2"
              echo "  - File 3: $file3"
              echo "  - Time diffs: $diff1_2 min, $diff2_3 min"
              echo "---"
              continue 3
            fi
            ;;
        esac
      done
    done
  done
}

# Run the triplet-finding logic for each list
process_triplets nps_files "North Pole (nps) Triplets" > nps_tandem_triplets.txt
process_triplets sps_files "South Pole (sps) Triplets" > sps_tandem_triplets.txt
