/**
 * Перед `electron-builder --mac`: npm ставит sharp только под CPU хоста.
 * В release идут x64 и arm64 — в .app должны быть оба набора @img/sharp-darwin-*.
 */
import { execFileSync } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const MAC_SHARP_IMG_PACKAGES = [
  '@img/sharp-darwin-arm64',
  '@img/sharp-libvips-darwin-arm64',
  '@img/sharp-darwin-x64',
  '@img/sharp-libvips-darwin-x64',
];

/**
 * @param {string} root
 * @returns {string[]} entries like `@img/sharp-darwin-x64@0.34.5` missing under node_modules
 */
export function macSharpImgPackagesToInstall(root) {
  const sharpPkgPath = path.join(root, 'node_modules', 'sharp', 'package.json');
  if (!fs.existsSync(sharpPkgPath)) {
    throw new Error('[release-mac-prep] sharp is not installed — run npm ci first');
  }

  const sharpPkg = JSON.parse(fs.readFileSync(sharpPkgPath, 'utf8'));
  const versions = sharpPkg.optionalDependencies ?? {};
  const missing = [];

  for (const name of MAC_SHARP_IMG_PACKAGES) {
    const version = versions[name];
    if (!version) {
      throw new Error(`[release-mac-prep] sharp optionalDependency missing: ${name}`);
    }
    if (!fs.existsSync(path.join(root, 'node_modules', name))) {
      missing.push(`${name}@${version}`);
    }
  }

  return missing;
}

/**
 * @param {string} root
 * @param {{ runInstall?: boolean }} [opts]
 */
export function ensureMacSharpBinaries(root, opts = {}) {
  const { runInstall = true } = opts;
  const toInstall = macSharpImgPackagesToInstall(root);

  if (toInstall.length === 0) {
    console.log('[release-mac-prep] all macOS sharp binaries present');
    return;
  }

  console.log('[release-mac-prep] installing', toInstall.join(', '));
  if (!runInstall) return;

  execFileSync('npm', ['install', '--no-save', '--force', ...toInstall], {
    cwd: root,
    stdio: 'inherit',
  });
}

const isMain = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url);
if (isMain) {
  const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
  if (process.platform !== 'darwin') {
    console.warn('[release-mac-prep] skipped: not macOS (no dual-arch sharp prep needed here)');
    process.exit(0);
  }
  ensureMacSharpBinaries(root);
}
