export function compareSemver(left: string, right: string): number {
  const leftParts = left.split('.').map((segment) => Number.parseInt(segment, 10));
  const rightParts = right.split('.').map((segment) => Number.parseInt(segment, 10));
  const length = Math.max(leftParts.length, rightParts.length);

  for (let i = 0; i < length; i++) {
    const a = Number.isFinite(leftParts[i]) ? leftParts[i]! : 0;
    const b = Number.isFinite(rightParts[i]) ? rightParts[i]! : 0;
    if (a > b) return 1;
    if (a < b) return -1;
  }

  return 0;
}

export function maxSemver(versions: string[]): string | null {
  if (versions.length === 0) {
    return null;
  }

  let max = versions[0]!;
  for (const version of versions.slice(1)) {
    if (compareSemver(version, max) > 0) {
      max = version;
    }
  }
  return max;
}
