'use strict';

module.exports = findRoot;

var fs = require('then-fs');
var path = require('path');
var debug = require('debug')('clite');

function findRoot(paths) {
  return Promise.resolve().then(function () {
    var root = null;

    do {
      // strip the `node_modules`
      var dir = path.resolve(paths.shift(), '..');
      debug(dir);
      var filename = path.resolve(dir, 'package.json');
      try {
        fs.statSync(filename);
        root = dir;
        break;
      } catch (e) {
        if (paths.length) {
          return findRoot(paths);
        }

        throw e;
      }
    } while (paths.length);

    debug('root is %s', root);
    return root;
  });
}