// Shared test/bench infrastructure
var fd = use('fd')
var pkg = use('package')

// Check if current directory is a valid cell package
function is_valid_package(dir) {
  var _dir = dir == null ? '.' : dir
  if (!_dir) _dir = '.'
  return fd.is_file(_dir + '/cell.toml')
}

// Get current package name from cell.toml or null
function get_current_package_name() {
  if (!is_valid_package('.')) return null
  var _load = function() {
    var config = pkg.load_config(null)
    return config.package || 'local'
  } disruption {
    return 'local'
  }
  return _load()
}

// Get the directory for a package
function get_pkg_dir(package_name) {
  if (!package_name) {
    return fd.realpath('.')
  }
  if (starts_with(package_name, '/')) {
    return package_name
  }
  var shop = use('internal/shop')
  return shop.get_package_dir(package_name)
}

// Ensure directory exists
function ensure_dir(path) {
  if (fd.is_dir(path)) return true

  var parts = array(path, '/')
  var current = starts_with(path, '/') ? '/' : ''
  var i = 0
  for (i = 0; i < length(parts); i++) {
    if (parts[i] == '') continue
    current = current + parts[i] + '/'
    if (!fd.is_dir(current)) {
      fd.mkdir(current)
    }
  }
  return true
}

return {
  is_valid_package: is_valid_package,
  get_current_package_name: get_current_package_name,
  get_pkg_dir: get_pkg_dir,
  ensure_dir: ensure_dir
}
