import path__default from 'node:path';
import { fileURLToPath } from 'node:url';
import { locatePath } from '../../../locate-path@7.1.0/node_modules/locate-path/index.mjs';

const toPath = urlOrPath => urlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath;
const findUpStop = Symbol('findUpStop');
async function findUpMultiple(name, options = {}) {
  let directory = path__default.resolve(toPath(options.cwd) || '');
  const {
    root
  } = path__default.parse(directory);
  const stopAt = path__default.resolve(directory, options.stopAt || root);
  const limit = options.limit || Number.POSITIVE_INFINITY;
  const paths = [name].flat();
  const runMatcher = async locateOptions => {
    {
      return locatePath(paths, locateOptions);
    }
  };
  const matches = [];
  // eslint-disable-next-line no-constant-condition
  while (true) {
    // eslint-disable-next-line no-await-in-loop
    const foundPath = await runMatcher({
      ...options,
      cwd: directory
    });
    if (foundPath === findUpStop) {
      break;
    }
    if (foundPath) {
      matches.push(path__default.resolve(directory, foundPath));
    }
    if (directory === stopAt || matches.length >= limit) {
      break;
    }
    directory = path__default.dirname(directory);
  }
  return matches;
}
async function findUp(name, options = {}) {
  const matches = await findUpMultiple(name, {
    ...options,
    limit: 1
  });
  return matches[0];
}

export { findUp, findUpMultiple, findUpStop };
