import _regeneratorRuntime from '@babel/runtime/regenerator';
import { _ as __awaiter } from '../tslib.es6-848120af.js';
import { getFs } from '../nodejs/fs.mjs';
import { getDotenv } from '../third-party/dotenv.mjs';
import { fetchRainbowConfig } from './rainbow-user.mjs';
import 'axios';
import '../list/flat.mjs';
import '@babel/runtime/helpers/toConsumableArray';
import '@babel/runtime/helpers/typeof';
import './helper/helper.mjs';
import './sdk.mjs';
import '../json/json-parse.mjs';

function writeEnvFromRainbow(_ref) {
  var envPath = _ref.envPath,
    rainbowAppId = _ref.rainbowAppId,
    rainbowUserId = _ref.rainbowUserId,
    rainbowSecretKey = _ref.rainbowSecretKey,
    rainbowKey = _ref.rainbowKey,
    envName = _ref.envName,
    groupName = _ref.groupName,
    sdk = _ref.sdk;
  return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
    var appId, userId, secretKey, str;
    return _regeneratorRuntime.wrap(function (_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          readLocalEnv(envPath);
          appId = rainbowAppId || process.env.RAINBOW_APP_ID || '';
          userId = rainbowUserId || process.env.RAINBOW_USER_ID || '';
          secretKey = rainbowSecretKey || process.env.RAINBOW_SECRET_KEY || '';
          if (appId) {
            _context.next = 1;
            break;
          }
          throw new Error('缺少 RAINBOW_APP_ID');
        case 1:
          _context.next = 2;
          return fetchRainbowConfig(rainbowKey, {
            appId: appId,
            envName: envName,
            groupName: groupName,
            userId: userId,
            secretKey: secretKey
          }, {
            sdk: sdk
          })["catch"](function (err) {
            console.log('[fetchRainbowConfig] err', err);
          });
        case 2:
          str = _context.sent;
          getFs().writeFileSync(envPath, str, {
            encoding: 'utf-8'
          });
          readLocalEnv(envPath);
          return _context.abrupt("return", true);
        case 3:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
}
function readLocalEnv(envPath) {
  getDotenv().config({
    path: envPath
  });
}

export { writeEnvFromRainbow };
