const { Bootstrap } = require('@midwayjs/bootstrap');
const { loadExternalConfig } = require('./dist/comm/config-loader');
const { resolveTraySecret } = require('./dist/comm/runtime-secret');

const traySecret = resolveTraySecret(process.argv, process.env);
if (traySecret) {
  process.env.GPU_GUARD_TRAY_SECRET = traySecret;
}
if (process.argv.includes('--no-browser')) {
  process.env.GPU_GUARD_NO_BROWSER = 'true';
}

if (process.argv.includes('--version')) {
  process.stdout.write(`${require('./package.json').version}\n`);
  process.exit(0);
}

const configArgIndex = process.argv.indexOf('--config');
if (configArgIndex > -1 && process.argv[configArgIndex + 1]) {
  process.env.GPU_GUARD_CONFIG_PATH = process.argv[configArgIndex + 1];
}

try {
  const loaded = loadExternalConfig();
  global.__NETA_EXTERNAL_CONFIG__ = loaded;
  process.env.NETA_DATA_DIR = loaded.data.dir;
} catch (error) {
  const msg = error.message || String(error);
  process.stderr.write(msg + '\n');
  if (process.pkg && process.platform === 'win32') {
    try {
      require('child_process').execSync(
        `msg * /TIME:30 "Neta 启动失败：${msg.replace(/"/g, "'")}"`,
        { stdio: 'ignore' }
      );
    } catch {
      require('child_process').spawnSync('cmd.exe', ['/c', 'pause'], { stdio: 'inherit' });
    }
  }
  process.exit(1);
}

// 显式以组件方式引入用户代码
Bootstrap.configure({
  // 这里引用的是编译后的入口，本地开发不走这个文件
  // eslint-disable-next-line node/no-unpublished-require
  imports: require('./dist/index'),
  // 禁用依赖注入的目录扫描
  moduleDetector: false,
}).run();
