#!/usr/bin/env node

const {existsSync} = require(`fs`);
const {createRequire, register} = require(`module`);
const {resolve} = require(`path`);
const {pathToFileURL} = require(`url`);

const relPnpApiPath = "../../../../.pnp.cjs";

const absPnpApiPath = resolve(__dirname, relPnpApiPath);
const absUserWrapperPath = resolve(__dirname, `./sdk.user.cjs`);
const absRequire = createRequire(absPnpApiPath);

const absPnpLoaderPath = resolve(absPnpApiPath, `../.pnp.loader.mjs`);
const isPnpLoaderEnabled = existsSync(absPnpLoaderPath);

if (existsSync(absPnpApiPath)) {
  if (!process.versions.pnp) {
    // Setup the environment to be able to require oxfmt
    require(absPnpApiPath).setup();
    if (isPnpLoaderEnabled && register) {
      register(pathToFileURL(absPnpLoaderPath));
    }
  }

  if (typeof global[`__yarnpkg_sdk_has_setup_env__`] === `undefined`) {
    Object.defineProperty(global, `__yarnpkg_sdk_has_setup_env__`, {configurable: true, value: true});

    process.env.NODE_OPTIONS = process.env.NODE_OPTIONS || ``;
    process.env.NODE_OPTIONS += ` -r ${absPnpApiPath}`;
    if (isPnpLoaderEnabled && register) {
      process.env.NODE_OPTIONS += ` --experimental-loader ${pathToFileURL(absPnpLoaderPath)}`;
    }
  }
}

const wrapWithUserWrapper = existsSync(absUserWrapperPath)
  ? exports => absRequire(absUserWrapperPath)(exports)
  : exports => exports;

const moduleWrapper = exports => {
  return wrapWithUserWrapper(moduleWrapperFn(exports));
};

const moduleWrapperFn = module => module;

const binPath = resolve(absRequire.resolve(`oxfmt/package.json`), `..`, `bin/oxfmt`);
absRequire(binPath);

// Defer to the real oxfmt your application uses
module.exports = moduleWrapper(absRequire(`oxfmt`));
