#!/usr/bin/env node
import fs from 'fs';
import path from 'path';
import { spawnSync } from 'child_process';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const projectRoot = path.resolve(__dirname, '..');
const prepareScript = path.join(projectRoot, 'scripts', 'prepare-electron-browsers.js');
const iconScript = path.join(projectRoot, 'scripts', 'build-icon.js');
const electronBuilderBin = path.join(
  projectRoot,
  'node_modules',
  '.bin',
  process.platform === 'win32' ? 'electron-builder.cmd' : 'electron-builder'
);
const electronVersion = JSON.parse(
  fs.readFileSync(path.join(projectRoot, 'node_modules', 'electron', 'package.json'), 'utf8')
).version;
const electronDistDir = path.join(projectRoot, '.electron-build', 'electron-dist');

const rawArgs = process.argv.slice(2);
const targets = rawArgs.filter((arg) => !arg.startsWith('--'));
const allArch = rawArgs.includes('--all-arch');
const buildArch = process.arch === 'arm64' ? 'arm64' : 'x64';
const archFlag = buildArch === 'arm64' ? '--arm64' : '--x64';
const builderArgs = ['--mac', ...(targets.length ? targets : ['dmg', 'zip'])];
if (!allArch) builderArgs.push(archFlag);

const env = {
  ...process.env,
  CSC_IDENTITY_AUTO_DISCOVERY: 'false',
};

function run(command, args) {
  return spawnSync(command, args, {
    cwd: projectRoot,
    stdio: 'inherit',
    env,
  });
}

function ensureElectronDistZip(arch) {
  fs.mkdirSync(electronDistDir, { recursive: true });
  const zipName = `electron-v${electronVersion}-darwin-${arch}.zip`;
  const zipPath = path.join(electronDistDir, zipName);
  if (fs.existsSync(zipPath) && fs.statSync(zipPath).size > 50 * 1024 * 1024) {
    return zipPath;
  }

  const url = `https://github.com/electron/electron/releases/download/v${electronVersion}/${zipName}`;
  const curlArgs = [
    '-L',
    '--fail',
    '--retry', '5',
    '--retry-delay', '2',
    '--continue-at', '-',
    '--output', zipPath,
    url,
  ];
  const result = run('curl', curlArgs);
  if (result.status !== 0) {
    process.exit(result.status || 1);
  }
  return zipPath;
}

const prepare = run(process.execPath, [prepareScript]);
if (prepare.status !== 0) {
  process.exit(prepare.status || 1);
}

const iconBuild = run(process.execPath, [iconScript]);
if (iconBuild.status !== 0) {
  process.exit(iconBuild.status || 1);
}

if (!allArch) {
  const zipPath = ensureElectronDistZip(buildArch);
  builderArgs.push(`-c.electronDist=${zipPath}`);
}

for (let attempt = 1; attempt <= 2; attempt++) {
  if (attempt > 1) {
    console.log(`[build-mac] Retry ${attempt}/2...`);
  }
  const result = run(electronBuilderBin, builderArgs);
  if (result.status === 0) {
    process.exit(0);
  }
  if (attempt === 2) {
    process.exit(result.status || 1);
  }
}
