const { chalk, log, getRegistryUrl } = require('./common.cjs');
async function main() {
  try {
    // const { execSync } = require('child_process');
    const path = require('path');
    const fs = require('fs');
    //const { default: chalk } = await import("chalk");
    await log('prepublish.js for ' + process.env.npm_package_name + ' started...', 'green')

    const ORIG_PKG_PATH = path.resolve(__dirname, '../../package.json');
    const TEMP_PKG_PATH = path.resolve(__dirname, '../../packagetemp.json');
    await log('package: ' + ORIG_PKG_PATH)
    await log('packagetemp: ' + TEMP_PKG_PATH)
    const origPkgData = require(ORIG_PKG_PATH);
    var origPkgDataString = JSON.stringify(origPkgData, null, 2)
    fs.writeFileSync(TEMP_PKG_PATH, origPkgDataString);
    await log('package.json copied to packagetemp.json')
    const senchaRegistryUrl = getRegistryUrl('@sencha');
    await log('@sencha is pointing to ' + chalk['yellow'](senchaRegistryUrl))
    delete origPkgData.eslintConfig;
    await log('remove eslintConfig from package.json')
    delete origPkgData.devDependencies;
    await log('remove devDependencies from package.json')
    delete origPkgData.dependencies;
    await log('remove dependencies from package.json')
    for (const scriptName in origPkgData.scripts) {
      if (origPkgData.scripts.hasOwnProperty(scriptName)) {
        if (scriptName.startsWith('pre') || scriptName.startsWith('post')) {
          // skip
        }
        else {
          delete origPkgData.scripts[scriptName]
        }
      }
    }
    await log('remove scripts not pre or post from package.json')
    var p = JSON.stringify(origPkgData, null, 2)
    // await log('published package.json: \n' + chalk['yellow'](p))
    fs.writeFileSync(ORIG_PKG_PATH, p);

    await log('prepublish.js for ' + process.env.npm_package_name + ' completed...\n', 'green')
  }
  catch (e) {
    console.log('* ReExt: - error: ' + e.toString())
  }
}
main();
