import { promisify } from 'util';
import { execFile } from 'child_process';
import * as os from 'os';

export async function checkRosetta() {
  if (process.platform !== 'darwin') {
    return false;
  }
  const execFileAsync = promisify(execFile);
  const sysctlRosettaInfoKey = 'sysctl.proc_translated';
  let isRosetta = false;
  try {
    console.log('Checking for macOS Rosetta environment');
    const result = await execFileAsync('sysctl', [sysctlRosettaInfoKey], { encoding: 'utf8' });
    isRosetta = result.stdout.includes(`${sysctlRosettaInfoKey}: 1`);
    console.log(`Checked for macOS Rosetta environment (isRosetta=${isRosetta})`);
  } catch (e) {
    console.error(`sysctl shell command to check for macOS Rosetta environment failed: ${e}`);
  }
  return isRosetta;
}

export async function getArch() {
  const execFileAsync = promisify(execFile);
  const archFromOs = os.arch();
  if (archFromOs !== 'x64' || process.platform !== 'darwin') {
    // not mac or real x64
    return archFromOs;
  }

  const isRosetta = await checkRosetta();

  let isArm64Mac = false;
  try {
    console.log('Checking for arm64 in uname');
    const result = await execFileAsync('uname', ['-a'], { encoding: 'utf8' });
    const isArm = result.stdout.includes('ARM');
    console.log(`Checked 'uname -a': arm64=${isArm}`);
    isArm64Mac = isArm64Mac || isArm;
  } catch (e) {
    console.error(`uname shell command to check for arm64 failed: ${e}`);
  }

  isArm64Mac = isArm64Mac || process.arch === 'arm64' || isRosetta;
  return isArm64Mac ? 'arm64' : archFromOs;
}