#!/bin/bash
# Keep only the latest version for each file pattern like ID_vVERSION.json

dir="${1:-.}"  # default to current directory
cd "$dir" || { echo "Error: Directory not found."; exit 1; }

echo "Scanning directory: $dir"
echo

# Extract base IDs (before _v)
for base in $(ls *_v*.json 2>/dev/null | sed -E 's/_v[0-9]+\.json//' | sort -u); do
  # List all versions for that base
  versions=($(ls ${base}_v*.json 2>/dev/null | sed -E 's/.*_v([0-9]+)\.json/\1/' | sort -n))

  # Skip if no versions found
  [[ ${#versions[@]} -eq 0 ]] && continue

  # Get the latest version number
  latest="${versions[-1]}"
  latest_file="${base}_v${latest}.json"

  echo "Keeping:   $latest_file"

  # Remove all older versions
  for v in "${versions[@]:0:${#versions[@]}-1}"; do
    old_file="${base}_v${v}.json"
    echo "Removing:  $old_file"
    rm -f "$old_file"
  done

  echo
done

echo "Cleanup complete!"
