import { getSubmodulePathList } from '../git/submodule.mjs';
import { execCommand } from '../node/node-command.mjs';
import { getFs } from '../nodejs/fs.mjs';
import { getPath } from '../nodejs/path.mjs';
import '../fs/fs.mjs';
import '../nodejs/crypto.mjs';
import '../nodejs/os.mjs';
import '@babel/runtime/helpers/typeof';
import '../nodejs/child_process.mjs';

function getSubmodulePathStr(file) {
  var submodules = getSubmodulePathList(file);
  var str = "\n".concat(submodules.map(function (item) {
    return "".concat(item, "/*");
  }).join('\n'));
  return str;
}
/**
 * 检查 ignore 文件是否已包含 submodule 忽略内容，
 * 只有不存在或未包含时才追加，避免重复写入
 */
function appendIgnoreIfNeeded(ignoreFile, contentToAppend, root) {
  var fs = getFs();
  var path = getPath();
  var fullPath = path.resolve(root, ignoreFile);
  try {
    if (fs.existsSync(fullPath)) {
      var existing = fs.readFileSync(fullPath, 'utf-8');
      // 取 contentToAppend 中的路径行进行检查
      var lines = contentToAppend.split('\n').filter(function (l) {
        return l.trim();
      });
      var alreadyExists = lines.length > 0 && lines.every(function (line) {
        return existing.includes(line);
      });
      if (alreadyExists) {
        console.log("[ignoreSubmodule] ".concat(ignoreFile, " \u5DF2\u5305\u542B submodule \u5FFD\u7565\u5185\u5BB9\uFF0C\u8DF3\u8FC7"));
        return;
      }
    }
  } catch (_a) {
    // 文件不存在或读取失败，继续追加
  }
  execCommand("echo \"".concat(contentToAppend, "\" >> ").concat(ignoreFile), root, 'inherit');
}
function ignoreSubmoduleInESLint() {
  var root = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : process.cwd();
  var str = getSubmodulePathStr(getPath().resolve(root, '.gitmodules'));
  appendIgnoreIfNeeded('.eslintignore', str, root);
}
function ignoreSubmoduleInStyleLint() {
  var root = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : process.cwd();
  var str = getSubmodulePathStr(getPath().resolve(root, '.gitmodules'));
  appendIgnoreIfNeeded('.stylelintignore', str, root);
}

export { ignoreSubmoduleInESLint, ignoreSubmoduleInStyleLint };
