#!/bin/bash

set -euo pipefail
set -xuve

# Function to remap the land cover classification data to a specified resolution and handle negative values
remap_and_handle_negative_values() {
  local ifile=$1
  local ofile=$2
  local year=$3
  local resolution=$4
  local grid_file=$5
  local resolution_type=$6
  local version=$7
  local tmp_prefix="tmp"
  local ovar="lccs_class"
  
  echo "Starting remap_and_handle_negative_values for year: ${year} with resolution type: ${resolution_type} and version: ${version}"

  # Clean up any existing temporary files
  rm -f ${tmp_prefix}?.nc

  # Check version and run ncap2 command if version is "207b"
  if [[ $version == "207b" ]]; then
    # Convert the file to ubyte 
    ncap2 -D 10 -4 -L 2 -O -s "lccs_class=ubyte(lccs_class)" ${ifile} ${tmp_prefix}2.nc
  else
    cp ${ifile} ${tmp_prefix}2.nc
  fi

  # Perform the remapping using gdalwarp
  echo "Executing gdalwarp..."
  if [[ $resolution_type == "f" ]]; then
    local tr=$(gdalinfo ${grid_file} | grep "Pixel Size" | awk -F'[()]' '{print $2}' | awk -F',' '{print $1, $2}')
    local xres=$(echo ${tr} | cut -d' ' -f1)
    local yres=$(echo ${tr} | cut -d' ' -f2)
    local xmin=-180.004464285714278
    local ymin=-89.99553571423947
    local xmax=179.9955357147926
    local ymax=89.99553571428301
    gdalwarp -overwrite -of netcdf -ot Byte -co FORMAT=NC4 -r mode -multi -wo NUM_THREADS=8 -t_srs EPSG:4326 -te ${xmin} ${ymin} ${xmax} ${ymax} -tr ${xres} ${yres} NETCDF:"${tmp_prefix}2.nc":${ovar} ${tmp_prefix}3.nc
  else
    local gdal_target_grid="-tr ${resolution} ${resolution}"
    gdalwarp -overwrite -of netcdf -ot Byte -co FORMAT=NC4 -r mode ${gdal_target_grid} -multi -wo NUM_THREADS=8 NETCDF:"${tmp_prefix}2.nc":${ovar} ${tmp_prefix}3.nc
  fi

  if [ $? -ne 0 ]; then
    echo "gdalwarp failed"
    exit 1
  fi
  echo "gdalwarp completed successfully."

  # Add time dimension to the file
  echo "Adding time dimension..."
  ncecat -u time ${tmp_prefix}3.nc ${tmp_prefix}4.nc
  ncap2 -O -s time[time]={0.0} ${tmp_prefix}4.nc ${tmp_prefix}5.nc
  ncatted -O -a units,time,o,c,"days since ${year}-01-01" ${tmp_prefix}5.nc
  echo "Time dimension added successfully."

  # Fix metadata using ncatted
  echo "Fixing metadata..."
  ncatted -h -a history,global,d,, ${tmp_prefix}5.nc
  ncatted -h -a history,global,c,c,"`date` : remapped to ${resolution} degrees resolution using gdalwarp and fixed metadata using nco" ${tmp_prefix}5.nc
  echo "Metadata fixed successfully."

  # Rename the variable to the original name
  echo "Renaming variables..."
  ncrename -h -v Band1,${ovar} ${tmp_prefix}5.nc
  if [ $? -ne 0 ]; then
    echo "ncrename failed"
    exit 1
  fi
  echo "Variables renamed successfully."

  # Add variable-specific metadata
  echo "Adding metadata..."
  ncatted -h -a long_name,${ovar},m,c,"Land cover class defined in LCCS" ${tmp_prefix}5.nc
  ncatted -h -a standard_name,${ovar},c,c,"land_cover_lccs" ${tmp_prefix}5.nc
  
  # Check version and run ncap2 command if version is "207b"
  if [[ $version == "207b" ]]; then
    # Convert the file to ubyte 
    ncap2 -O -s 'lccs_class@flag_values={0, 10, 11, 12, 20, 30, 40, 50, 60, 61, 62, 70, 71, 72, 80, 81, 82, 90, 100, 110, 120, 121, 122, 130, 140, 150, 151, 152, 153, 160, 170, 180, 190, 200, 201, 202, 210, 220}' ${tmp_prefix}5.nc ${tmp_prefix}6.nc
    ncap2 -O -s 'lccs_class@ancillary_variables="processed_flag current_pixel_state observation_count change_count"; lccs_class@flag_colors="#ffff64 #ffff64 #ffff00 #aaf0f0 #dcf064 #c8c864 #006400 #00a000 #00a000 #aac800 #003c00 #003c00 #005000 #285000 #285000 #286400 #788200 #8ca000 #be9600 #966400 #966400 #966400 #ffb432 #ffdcd2 #ffebaf #ffc864 #ffd278 #ffebaf #00785a #009678 #00dc82 #c31400 #fff5d7 #dcdcdc #fff5d7 #0046c8 #ffffff"' ${tmp_prefix}6.nc ${tmp_prefix}7.nc

  else
    cp ${tmp_prefix}5.nc ${tmp_prefix}7.nc
  fi
  echo "Metadata added successfully."

  # Move the final product to the output directory
  echo "Moving final product to output directory..."
  mv ${tmp_prefix}7.nc ${ofile}
  if [ $? -ne 0 ]; then
    echo "Failed to move the final product to the output directory"
    exit 1
  fi
  echo "Final product moved successfully."

  # Clean up temporary files
  echo "Cleaning up temporary files..."
  rm -f ${tmp_prefix}?.nc
  echo "Temporary files cleaned up."

  echo "Finished processing for year: ${year} with resolution type: ${resolution_type}"
}

# Parameters
ifile=$1
ofile=$2
tmpdir=$3
resolution=$4
year=$5
grid_file=$6
resolution_type=$7
version=$8

mkdir -p $tmpdir
cd $tmpdir


# Process files for the given year
remap_and_handle_negative_values ${ifile} ${ofile} ${year} ${resolution} ${grid_file} ${resolution_type} ${version}
