export interface ElectronAppMetricsProcess {
  pid: number;
  type: string;
  workingSetKb: number | null;
}

export interface ElectronAppMetricsSnapshot {
  collectedAt: number;
  processes: ElectronAppMetricsProcess[];
}

export function sumWorkingSetKb(processes: ElectronAppMetricsProcess[]): number | null {
  let total = 0;
  let hasAny = false;

  for (const process of processes) {
    if (process.workingSetKb == null || process.workingSetKb < 0)
      continue;

    total += process.workingSetKb;
    hasAny = true;
  }

  return hasAny ? total : null;
}

export function formatKilobytesAsMegabytes(kilobytes: number): string {
  const megabytes = kilobytes / 1024;

  if (megabytes >= 100)
    return `${Math.round(megabytes)} MB`;

  if (megabytes >= 10)
    return `${megabytes.toFixed(1)} MB`;

  return `${megabytes.toFixed(2)} MB`;
}

export function formatAppRamLabel(snapshot: ElectronAppMetricsSnapshot): string | null {
  const totalKb = sumWorkingSetKb(snapshot.processes);

  if (totalKb == null)
    return null;

  return formatKilobytesAsMegabytes(totalKb);
}
