'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _regeneratorRuntime = require('@babel/runtime/regenerator');
var tslib_es6 = require('../tslib.es6-0d92ef81.js');
var minimatch_minimatch = require('../minimatch/minimatch.js');
var fs_fs = require('../fs/fs.js');
require('../nodejs/crypto.js');
require('../nodejs/fs.js');
require('../nodejs/os.js');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var _regeneratorRuntime__default = /*#__PURE__*/_interopDefaultLegacy(_regeneratorRuntime);

/** 判断审核人是否有效（空或 'NONE' 均视为无需审核） */
function isValidAuditor(auditor) {
  return !!auditor && auditor !== 'NONE';
}
/** 解析配置数据源：支持文件路径（同步读取）或异步获取函数 */
function resolveConfig(configSource) {
  return tslib_es6.__awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee() {
    var _t;
    return _regeneratorRuntime__default["default"].wrap(function (_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          if (!(typeof configSource === 'function')) {
            _context.next = 2;
            break;
          }
          _context.next = 1;
          return configSource();
        case 1:
          _t = _context.sent;
          _context.next = 3;
          break;
        case 2:
          _t = fs_fs.readFileSync(configSource, true);
        case 3:
          return _context.abrupt("return", _t);
        case 4:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
}
/**
 * 统一审核人获取方法，支持 rainbow / json / static 三种模式
 *
 * @example rainbow 模式 - 文件路径
 * ```ts
 * const { auditor, shouldAudit } = await getAuditor({
 *   type: 'rainbow',
 *   configSource: '/data/h5_publish_auditor.json',
 *   rainbowOptions: { projectName: 'pmd-mobile/match/gp', subProjectName: 'gp-hor', minimatch },
 * });
 * ```
 *
 * @example rainbow 模式 - 异步获取数据
 * ```ts
 * const { auditor, shouldAudit } = await getAuditor({
 *   type: 'rainbow',
 *   configSource: async () => fetchRainbowConfig(),
 *   rainbowOptions: { projectName: 'pmd-mobile/match/gp', subProjectName: 'gp-hor', minimatch },
 * });
 * ```
 *
 * @example json 模式（NPM/组件库发布）
 * ```ts
 * const { auditor, shouldAudit } = await getAuditor({
 *   type: 'json',
 *   configSource: '/data/library_publish_auditor.json',
 *   jsonOptions: { projectName: 'my-lib', key: 'patch' },
 * });
 * ```
 *
 * @example static 模式（灰度发布 / 回滚）
 * ```ts
 * const { auditor, shouldAudit } = await getAuditor({
 *   type: 'static',
 *   staticAuditorList: ['novlan1', 'lee'],
 * });
 * ```
 *
 * @example 跳过审核（如非生产环境）
 * ```ts
 * const { auditor, shouldAudit } = await getAuditor({
 *   type: 'static',
 *   skipAudit: !isProd,
 * });
 * ```
 */
function getAuditor(options) {
  var _a;
  return tslib_es6.__awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee2() {
    var type, configSource, rainbowOptions, jsonOptions, staticAuditorList, _options$skipAudit, skipAudit, projectName, subProjectName, minimatch, auditKey, rainbowConfig, auditor, _projectName, key, data, _auditor, _auditor2;
    return _regeneratorRuntime__default["default"].wrap(function (_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          type = options.type, configSource = options.configSource, rainbowOptions = options.rainbowOptions, jsonOptions = options.jsonOptions, staticAuditorList = options.staticAuditorList, _options$skipAudit = options.skipAudit, skipAudit = _options$skipAudit === void 0 ? false : _options$skipAudit; // 跳过审核
          if (!skipAudit) {
            _context2.next = 1;
            break;
          }
          return _context2.abrupt("return", {
            auditor: '',
            shouldAudit: false
          });
        case 1:
          if (!(type === 'rainbow')) {
            _context2.next = 4;
            break;
          }
          if (!(!rainbowOptions || !configSource)) {
            _context2.next = 2;
            break;
          }
          return _context2.abrupt("return", {
            auditor: '',
            shouldAudit: false
          });
        case 2:
          projectName = rainbowOptions.projectName, subProjectName = rainbowOptions.subProjectName, minimatch = rainbowOptions.minimatch;
          auditKey = "".concat(projectName, "##").concat(subProjectName);
          _context2.next = 3;
          return resolveConfig(configSource);
        case 3:
          rainbowConfig = _context2.sent;
          console.log('[getAuditor][rainbowConfig]', rainbowConfig);
          auditor = minimatch_minimatch.getAuditorFromRainbowConfig({
            rainbowConfig: rainbowConfig,
            checkKeyList: [auditKey, projectName],
            minimatch: minimatch,
            minimatchKey: projectName
          });
          console.log('[getAuditor][auditor]', auditor);
          return _context2.abrupt("return", {
            auditor: auditor || '',
            shouldAudit: isValidAuditor(auditor || '')
          });
        case 4:
          if (!(type === 'json')) {
            _context2.next = 7;
            break;
          }
          if (!(!jsonOptions || !configSource)) {
            _context2.next = 5;
            break;
          }
          return _context2.abrupt("return", {
            auditor: '',
            shouldAudit: false
          });
        case 5:
          _projectName = jsonOptions.projectName, key = jsonOptions.key;
          _context2.next = 6;
          return resolveConfig(configSource);
        case 6:
          data = _context2.sent;
          _auditor = ((_a = data === null || data === void 0 ? void 0 : data[_projectName]) === null || _a === void 0 ? void 0 : _a[key]) || '';
          return _context2.abrupt("return", {
            auditor: _auditor,
            shouldAudit: isValidAuditor(_auditor)
          });
        case 7:
          if (!(type === 'static')) {
            _context2.next = 8;
            break;
          }
          _auditor2 = (staticAuditorList || []).join(',');
          return _context2.abrupt("return", {
            auditor: _auditor2,
            shouldAudit: isValidAuditor(_auditor2)
          });
        case 8:
          return _context2.abrupt("return", {
            auditor: '',
            shouldAudit: false
          });
        case 9:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  }));
}
/**
 * 转义审核描述中的反引号，防止在企微消息中出错
 *
 * @example
 * ```ts
 * escapeAuditDesc('修复`bug`')  // => '修复\\`bug\\`'
 * ```
 */
function escapeAuditDesc(desc) {
  return (desc || '').replace(/`/g, '\\`');
}

exports.escapeAuditDesc = escapeAuditDesc;
exports.getAuditor = getAuditor;
