/*
 * Copyright (C) 2026 SFG545
 *
 * This file is part of Orchard and is licensed under the GNU AGPL v3 or later.
 */

import semver from 'semver';

export const DEFAULT_PACKAGE_SERVICE_URL = 'https://pub-313e2044e34f435289be12e90b5ef0d7.r2.dev/';

export function packageServiceTarget(platform = process.platform, architecture = process.arch) {
  const normalizedPlatform = platform === 'win32' ? 'win32' : platform;
  const normalizedArchitecture = architecture === 'x64' || architecture === 'amd64'
    ? 'x64'
    : architecture === 'arm64' || architecture === 'aarch64'
      ? 'arm64'
      : architecture;
  return `${normalizedPlatform}-${normalizedArchitecture}`;
}

export function selectPackageServiceRelease(manifest, { channel, currentVersion, target }) {
  if (manifest?.schemaVersion !== 1 || !Array.isArray(manifest.releases)) {
    throw new Error('The Orchard package manifest is invalid.');
  }

  const releases = manifest.releases
    .filter((release) => release?.channel === channel && release?.native?.[target])
    .filter((release) => semver.valid(release.version))
    .sort((left, right) => semver.rcompare(left.version, right.version));
  const latest = releases[0] || null;
  const installedVersion = semver.valid(currentVersion) || semver.coerce(currentVersion)?.version || '0.0.0';
  return {
    latest,
    updateAvailable: Boolean(latest && semver.gt(latest.version, installedVersion))
  };
}
