package com.foxx.androidcast;

/*********************************************************************
 * VersionUtils.java
 * Created at: Sat 16 May 2026 13:35:48 +0200
 * Updated at: Wed 20 May 2026 15:17:13 +0200 by Anton Afanasyeu <a.afanasieff@gmail.com>
 * Commit: 5d8e82d2e60a21fff3138d2a394ee4e8b4c6dcb8
 * class VersionUtils
 * Contributors:
 *    - Anton Afanasyeu <a.afanasieff@gmail.com> (2 commits, 71 lines)
 *    - Cursor Agent (project assistant)
 * Digest: SHA256	fa3c418e4af4fb3f570ffff62380bae9f11c86b08ddc2d6cad397d4be2a9a435
**********************************************************************/
import java.util.Locale;

/**
 * Version string format {@code PP.MM.mmmm.BBBB} (e.g. {@code 00.01.0003.5621}) packed into uint64.
 * Layout: placeholder(2) · major(2) · minor(4) · build(4) decimal digits.
 */
public final class VersionUtils {
  private VersionUtils() {}

  public static String format(int placeholder, int major, int minor, int build) {
    return String.format(Locale.US, "%02d.%02d.%04d.%04d",
        clamp(placeholder, 0, 99),
        clamp(major, 0, 99),
        clamp(minor, 0, 9999),
        clamp(build, 0, 9999));
  }

  public static long toInt(int placeholder, int major, int minor, int build) {
    long ph = clamp(placeholder, 0, 99);
    long maj = clamp(major, 0, 99);
    long min = clamp(minor, 0, 9999);
    long bld = clamp(build, 0, 9999);
    return ph * 10_000_000_000L + maj * 100_000_000L + min * 10_000L + bld;
  }

  public static long parseToInt(String version) {
    if (version == null || version.isEmpty()) {
      return 0L;
    }
    String[] parts = version.split("\\.");
    int ph = parts.length > 0 ? parsePart(parts[0], 0) : 0;
    int maj = parts.length > 1 ? parsePart(parts[1], 0) : 0;
    int min = parts.length > 2 ? parsePart(parts[2], 0) : 0;
    int bld = parts.length > 3 ? parsePart(parts[3], 0) : 0;
    return toInt(ph, maj, min, bld);
  }

  public static String formatFromInt(long packed) {
    if (packed < 0) {
      packed = 0;
    }
    int build = (int) (packed % 10_000L);
    packed /= 10_000L;
    int minor = (int) (packed % 10_000L);
    packed /= 10_000L;
    int major = (int) (packed % 100L);
    int placeholder = (int) (packed / 100L);
    return format(placeholder, major, minor, build);
  }

  private static int parsePart(String s, int fallback) {
    try {
      return Integer.parseInt(s.trim());
    } catch (NumberFormatException e) {
      return fallback;
    }
  }

  private static int clamp(int v, int min, int max) {
    return Math.max(min, Math.min(max, v));
  }
}
