import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
import _toArray from '@babel/runtime/helpers/toArray';
import _regeneratorRuntime from '@babel/runtime/regenerator';
import { _ as __awaiter } from '../tslib.es6-848120af.js';
import { writeFileSync } from '../fs/fs.mjs';
import { getChildProcess } from '../nodejs/child_process.mjs';
import { getFs } from '../nodejs/fs.mjs';
import { getPath } from '../nodejs/path.mjs';
import { uploadCOSFile } from '../tencent-cloud/cos/cos.mjs';
import { timeStampFormat } from '../time/time.mjs';
import '../nodejs/crypto.mjs';
import '../nodejs/os.mjs';
import '../tencent-cloud/cos/helper.mjs';
import '../bite/format-bite.mjs';
import '../third-party/cos-nodejs-sdk-v5.mjs';

function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function getGitLog(root, filePath) {
  var days = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 365 * 10;
  var since = new Date();
  since.setDate(since.getDate() - days);
  var sinceStr = since.toISOString().split('T')[0];
  var cmd = "git log --since=\"".concat(sinceStr, "\" --pretty=format:\"%H|%h|%an|%ae|%ad|%s|%b\" --date=format:'%Y-%m-%d %H:%M:%S' -- ").concat(filePath);
  var output = getChildProcess().execSync(cmd, {
    encoding: 'utf8',
    cwd: root
  });
  var commits = [];
  output.split('\n').forEach(function (line) {
    if (!line.trim()) return;
    var _line$split = line.split('|'),
      _line$split2 = _toArray(_line$split),
      hash = _line$split2[0],
      shortHash = _line$split2[1],
      author = _line$split2[2],
      email = _line$split2[3],
      date = _line$split2[4],
      subject = _line$split2[5],
      bodyParts = _line$split2.slice(6);
    var body = bodyParts.join('|').replace(/\n/g, '\\n');
    commits.push({
      hash: hash,
      shortHash: shortHash,
      author: author,
      email: email,
      date: date,
      subject: subject,
      body: body
    });
  });
  return commits;
}
function getDirs(root) {
  var dirs = getFs().readdirSync(root);
  return dirs;
}
/**
 * 统计代码库变更情况。分析多个项目的 Git 提交记录，生成统计数据并可选上传到 COS
 * @param analyzeList - 要分析的项目列表
 * @param saveDataDir - 保存统计数据的本地目录
 * @param cosInfo - COS 上传配置信息（可选）
 * @param cosInfo.secretId - 腾讯云 SecretId
 * @param cosInfo.secretKey - 腾讯云 SecretKey
 * @param cosInfo.bucket - COS 存储桶名称
 * @param cosInfo.region - COS 区域
 * @param cosInfo.dir - COS 目录路径
 * @param analyzeBlackList - 需要排除的目录黑名单（可选）
 * @returns {Promise<Array>} - 返回每个项目的统计结果数组
 * @example
 * ```ts
 * libraryChangeStatistics({
 *   analyzeList: [
 *     { root: '/path/to/repo', project: 'my-project', git: 'https://...' }
 *   ],
 *   saveDataDir: '/tmp/stats',
 *   cosInfo: {
 *     secretId: 'xxx',
 *     secretKey: 'xxx',
 *     bucket: 'my-bucket',
 *     region: 'ap-guangzhou',
 *     dir: 'stats'
 *   },
 *   analyzeBlackList: ['node_modules', 'dist']
 * }).then(result => {
 *   console.log('统计完成:', result);
 * });
 * ```
 */
function libraryChangeStatistics(_ref) {
  var analyzeList = _ref.analyzeList,
    saveDataDir = _ref.saveDataDir,
    cosInfo = _ref.cosInfo,
    analyzeBlackList = _ref.analyzeBlackList;
  return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
    var result, _iterator, _step, project, _yield$parseOneProjec, data, cdnLink, _t;
    return _regeneratorRuntime.wrap(function (_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          result = [];
          _iterator = _createForOfIteratorHelper(analyzeList);
          _context.prev = 1;
          _iterator.s();
        case 2:
          if ((_step = _iterator.n()).done) {
            _context.next = 5;
            break;
          }
          project = _step.value;
          _context.next = 3;
          return parseOneProject({
            project: project,
            saveDataDir: saveDataDir,
            cosInfo: cosInfo,
            analyzeBlackList: analyzeBlackList
          });
        case 3:
          _yield$parseOneProjec = _context.sent;
          data = _yield$parseOneProjec.result;
          cdnLink = _yield$parseOneProjec.cdnLink;
          result.push({
            data: data,
            project: project,
            cdnLink: cdnLink
          });
        case 4:
          _context.next = 2;
          break;
        case 5:
          _context.next = 7;
          break;
        case 6:
          _context.prev = 6;
          _t = _context["catch"](1);
          _iterator.e(_t);
        case 7:
          _context.prev = 7;
          _iterator.f();
          return _context.finish(7);
        case 8:
          return _context.abrupt("return", result);
        case 9:
        case "end":
          return _context.stop();
      }
    }, _callee, null, [[1, 6, 7, 8]]);
  }));
}
function getTargetAnalyzeDir(_ref2) {
  var root = _ref2.root,
    analyzeDir = _ref2.analyzeDir,
    needAnalyzeSubDir = _ref2.needAnalyzeSubDir,
    _ref2$analyzeBlackLis = _ref2.analyzeBlackList,
    analyzeBlackList = _ref2$analyzeBlackLis === void 0 ? [] : _ref2$analyzeBlackLis;
  if (!analyzeDir) {
    return [root];
  }
  var dirs = getDirs(getPath().resolve(root, analyzeDir));
  var targetAnalyzeDir = [];
  var _iterator2 = _createForOfIteratorHelper(dirs),
    _step2;
  try {
    var _loop = function _loop() {
      var dir = _step2.value;
      var srcDir = getPath().resolve(root, analyzeDir, dir, 'src');
      if (needAnalyzeSubDir === null || needAnalyzeSubDir === void 0 ? void 0 : needAnalyzeSubDir.includes(dir)) {
        targetAnalyzeDir.push.apply(targetAnalyzeDir, _toConsumableArray(getDirs(srcDir).filter(function (subDir) {
          return !analyzeBlackList.includes(subDir);
        }).map(function (subDir) {
          return getPath().resolve(srcDir, subDir);
        })));
      } else if (!getFs().existsSync(srcDir)) {
        targetAnalyzeDir.push(getPath().resolve(root, analyzeDir, dir));
      } else {
        targetAnalyzeDir.push(srcDir);
      }
    };
    for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
      _loop();
    }
  } catch (err) {
    _iterator2.e(err);
  } finally {
    _iterator2.f();
  }
  return targetAnalyzeDir;
}
function filterCommit() {
  var commits = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  return commits.filter(function (item) {
    var _a, _b;
    return !((_b = (_a = item.subject) === null || _a === void 0 ? void 0 : _a.includes) === null || _b === void 0 ? void 0 : _b.call(_a, 'chore(release): publish'));
  }).filter(function (item) {
    return item.email && item.author && item.hash;
  }).filter(function (item) {
    return item.author !== 'mobilehelper';
  });
}
function parseOneProject(_ref3) {
  var project = _ref3.project,
    saveDataDir = _ref3.saveDataDir,
    cosInfo = _ref3.cosInfo,
    analyzeBlackList = _ref3.analyzeBlackList;
  return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
    var root, _project$analyzeDir, analyzeDir, simpleRoot, needAnalyzeSubDir, targetAnalyzeDir, result, _iterator3, _step3, dir, commits, totalCommitsLength, cdnLink, targetJsonPath, cosName;
    return _regeneratorRuntime.wrap(function (_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          root = project.root, _project$analyzeDir = project.analyzeDir, analyzeDir = _project$analyzeDir === void 0 ? '' : _project$analyzeDir, simpleRoot = project.simpleRoot, needAnalyzeSubDir = project.needAnalyzeSubDir;
          targetAnalyzeDir = getTargetAnalyzeDir({
            root: root,
            analyzeDir: analyzeDir,
            needAnalyzeSubDir: needAnalyzeSubDir,
            analyzeBlackList: analyzeBlackList
          });
          console.log('[targetAnalyzeDir]', targetAnalyzeDir);
          result = [];
          _iterator3 = _createForOfIteratorHelper(targetAnalyzeDir);
          try {
            for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
              dir = _step3.value;
              commits = filterCommit(getGitLog(root, dir));
              result.push({
                project: project.project,
                commits: commits,
                commitsLength: commits.length,
                analyzeDir: getPath().relative(getPath().resolve(root), dir),
                git: project.git
              });
            }
          } catch (err) {
            _iterator3.e(err);
          } finally {
            _iterator3.f();
          }
          result.sort(function (a, b) {
            return b.commitsLength - a.commitsLength;
          });
          totalCommitsLength = result.reduce(function (sum, item) {
            return sum + item.commitsLength;
          }, 0);
          cdnLink = '';
          if (!saveDataDir) {
            _context2.next = 2;
            break;
          }
          if (!getFs().existsSync(saveDataDir)) {
            getFs().mkdirSync(saveDataDir, {
              recursive: true
            });
          }
          targetJsonPath = getPath().resolve(saveDataDir, "".concat(simpleRoot, ".json"));
          writeFileSync(targetJsonPath, {
            data: result,
            date: timeStampFormat(Date.now(), 'yyyy-MM-dd hh:mm:ss'),
            total: totalCommitsLength
          }, true);
          if (!cosInfo) {
            _context2.next = 2;
            break;
          }
          cosName = "".concat(cosInfo.dir, "/").concat(simpleRoot, ".json");
          console.log('[cosName]', cosName);
          console.log('[targetJsonPath]', targetJsonPath);
          _context2.next = 1;
          return uploadCOSFile({
            secretId: cosInfo.secretId,
            secretKey: cosInfo.secretKey,
            bucket: cosInfo.bucket,
            region: cosInfo.region,
            files: [{
              key: cosName,
              path: targetJsonPath
            }]
          });
        case 1:
          cdnLink = "https://image-1251917893.file.myqcloud.com/".concat(cosName);
        case 2:
          return _context2.abrupt("return", {
            cdnLink: cdnLink,
            result: result
          });
        case 3:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  }));
}

export { filterCommit, libraryChangeStatistics };
