// 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)
}

// Deep comparison of two values (handles arrays and objects)
function values_equal(a, b) {
  var i = 0
  var ka = null
  var kb = null
  if (a == b) return true
  if (is_null(a) && is_null(b)) return true
  if (is_null(a) || is_null(b)) return false
  if (is_array(a) && is_array(b)) {
    if (length(a) != length(b)) return false
    i = 0
    while (i < length(a)) {
      if (!values_equal(a[i], b[i])) return false
      i = i + 1
    }
    return true
  }
  if (is_object(a) && is_object(b)) {
    ka = array(a)
    kb = array(b)
    if (length(ka) != length(kb)) return false
    i = 0
    while (i < length(ka)) {
      if (!values_equal(a[ka[i]], b[ka[i]])) return false
      i = i + 1
    }
    return true
  }
  return false
}

// Describe a value for error messages
function describe(val) {
  if (is_null(val)) return "null"
  if (is_text(val)) return `"${val}"`
  if (is_number(val)) return text(val)
  if (is_logical(val)) return text(val)
  if (is_function(val)) return "<function>"
  if (is_array(val)) return `[array length=${text(length(val))}]`
  if (is_object(val)) return `{record keys=${text(length(array(val)))}}`
  return "<unknown>"
}

return {
  is_valid_package: is_valid_package,
  get_current_package_name: get_current_package_name,
  get_pkg_dir: get_pkg_dir,
  ensure_dir: fd.ensure_dir,
  values_equal: values_equal,
  describe: describe
}
