#!/usr/bin/env node
'use strict';

const fs = require('node:fs');
const path = require('node:path');
const { spawnSync } = require('node:child_process');

const packageRoot = path.resolve(__dirname, '..');
const harFile = path.join(packageRoot, 'harmony', 'dist', 'code_push.har');
const buildScript = path.join(__dirname, 'build-code-push-har.ps1');

function isFile(file) {
  try {
    const stat = fs.statSync(file);
    return stat.isFile() && stat.size > 0;
  } catch (_) {
    return false;
  }
}

function main() {
  const force = process.argv.includes('--force') || process.env.RNOH_FORCE_REBUILD === '1';
  if (!force && isFile(harFile)) {
    console.log('[code_push] harmony/dist/code_push.har already exists; skip build');
    return;
  }
  if (!isFile(buildScript)) {
    throw new Error(`CodePush HAR build script is missing: ${buildScript}`);
  }

  const executable = process.platform === 'win32' ? 'powershell' : 'pwsh';
  const result = spawnSync(executable, ['-ExecutionPolicy', 'Bypass', '-File', buildScript], {
    cwd: packageRoot,
    env: process.env,
    stdio: 'inherit',
    windowsHide: true,
  });
  if (result.error) throw result.error;
  if ((result.status ?? 1) !== 0) {
    throw new Error(`${path.basename(executable)} failed with exit code ${result.status}`);
  }
  if (!isFile(harFile)) {
    throw new Error(`CodePush HAR was not generated: ${harFile}`);
  }
}

try {
  main();
} catch (error) {
  console.error(`[code_push] ${error.message}`);
  process.exitCode = 1;
}