import process from 'node:process';
import fs__default from 'node:fs';
import path__default from 'node:path';
import fastGlob from '../../../../../_virtual/index3.mjs';
import gitIgnore from '../../../../../_virtual/index5.mjs';
import slash from '../../../slash@4.0.0/node_modules/slash/index.mjs';
import { toPath, isNegativePattern } from './utilities.mjs';

const ignoreFilesGlobOptions = {
  ignore: ['**/node_modules', '**/flow-typed', '**/coverage', '**/.git'],
  absolute: true,
  dot: true
};
const GITIGNORE_FILES_PATTERN = '**/.gitignore';
const applyBaseToPattern = (pattern, base) => isNegativePattern(pattern) ? '!' + path__default.posix.join(base, pattern.slice(1)) : path__default.posix.join(base, pattern);
const parseIgnoreFile = (file, cwd) => {
  const base = slash(path__default.relative(cwd, path__default.dirname(file.filePath)));
  return file.content.split(/\r?\n/).filter(line => line && !line.startsWith('#')).map(pattern => applyBaseToPattern(pattern, base));
};
const toRelativePath = (fileOrDirectory, cwd) => {
  cwd = slash(cwd);
  if (path__default.isAbsolute(fileOrDirectory)) {
    if (slash(fileOrDirectory).startsWith(cwd)) {
      return path__default.relative(cwd, fileOrDirectory);
    }
    throw new Error(`Path ${fileOrDirectory} is not in cwd ${cwd}`);
  }
  return fileOrDirectory;
};
const getIsIgnoredPredicate = (files, cwd) => {
  const patterns = files.flatMap(file => parseIgnoreFile(file, cwd));
  const ignores = gitIgnore().add(patterns);
  return fileOrDirectory => {
    fileOrDirectory = toPath(fileOrDirectory);
    fileOrDirectory = toRelativePath(fileOrDirectory, cwd);
    return fileOrDirectory ? ignores.ignores(slash(fileOrDirectory)) : false;
  };
};
const normalizeOptions = (options = {}) => ({
  cwd: toPath(options.cwd) || process.cwd(),
  suppressErrors: Boolean(options.suppressErrors),
  deep: typeof options.deep === 'number' ? options.deep : Number.POSITIVE_INFINITY
});
const isIgnoredByIgnoreFiles = async (patterns, options) => {
  const {
    cwd,
    suppressErrors,
    deep
  } = normalizeOptions(options);
  const paths = await fastGlob(patterns, {
    cwd,
    suppressErrors,
    deep,
    ...ignoreFilesGlobOptions
  });
  const files = await Promise.all(paths.map(async filePath => ({
    filePath,
    content: await fs__default.promises.readFile(filePath, 'utf8')
  })));
  return getIsIgnoredPredicate(files, cwd);
};

export { GITIGNORE_FILES_PATTERN, isIgnoredByIgnoreFiles };
