#!/usr/bin/env bash

#MISE description="Show outdated dependencies."

# We purposefully do not set `set -e` here, as we want to see all outdated dependencies at once.

source "$(git rev-parse --show-toplevel)/scripts/_helpers.sh"

ensure_working_directory!

# Initialize arrays to track commands
declare -a command_names
declare -a command_results
declare -a command_next_steps

# Function to run and track commands
run_and_track() {
  local name="$1"
  local next_step="$2"
  shift 2
  "$@"
  local result=$?
  command_names+=("$name")
  command_results+=("$result")
  command_next_steps+=("$next_step")
  return $result
}

debug_msg "Checking outdated NPM dependencies..."
run_and_track "NPM dependencies" "npm update --prefix assets" npm outdated --prefix assets

debug_msg "Checking outdated tooling (tailwind, esbuild, sqlean)..."
run_and_track "Tailwind" "mix tailwind.update_version" mix tailwind.check_version
run_and_track "ESBuild" "mix esbuild.update_version" mix esbuild.check_version
run_and_track "Sqlean" "mix sqlean.update_version" mix sqlean.check_version

debug_msg "Checking outdated mix dependencies"
run_and_track "Mix dependencies" "mix deps.update --all" mix hex.outdated --all

debug_msg "Checking outdated pi s3-browser dependencies..."
run_and_track "pi s3-browser dependencies" \
  "npm update --prefix .pi/extensions/s3-browser" \
  npm outdated --prefix .pi/extensions/s3-browser

debug_msg "Checking outdated pi sensitive-file-guard dependencies..."
run_and_track "pi sensitive-file-guard dependencies" \
  "npm update --prefix .pi/extensions/sensitive-file-guard" \
  npm outdated --prefix .pi/extensions/sensitive-file-guard

# Print summary table
echo ""
echo "========================================================================"
echo "Summary"
echo "========================================================================"
printf "%-36s | %-16s | %s\n" "Dependency" "Status" "Next Step"
echo "------------------------------------------------------------------------"

red=$(tput setaf 1)
green=$(tput setaf 2)
normal=$(tput sgr0)

for i in "${!command_names[@]}"; do
  name="${command_names[$i]}"
  result="${command_results[$i]}"
  next_step="${command_next_steps[$i]}"

  if [ "$result" -eq 0 ]; then
    printf "%-36s | %s%-18s%s | %s\n" "$name" "$green" "✓ Up to date" "$normal" "Nothing to do"
  else
    printf "%-36s | %s%-18s%s | %s\n" "$name" "$red" "✗ Outdated" "$normal" "$next_step"
  fi
done

echo "========================================================================"

# Print footer hint if anything is outdated
for result in "${command_results[@]}"; do
  if [ "$result" -ne 0 ]; then
    echo ""
    echo "To update everything, run \`mise run dev:update\`"
    break
  fi
done
