// cell install <locator> - Install a package to the shop
// Does not modify the current project's cell.toml

var shop = use('internal/shop')
var build = use('build')
var fd = use('fd')

if (args.length < 1) {
  log.console("Usage: cell install <locator>")
  $stop()
  return
}

var locator = args[0]

// Resolve relative paths to absolute paths
// Local paths like '.' or '../foo' need to be converted to absolute paths
if (locator == '.' || locator.startsWith('./') || locator.startsWith('../') || fd.is_dir(locator)) {
  var resolved = fd.realpath(locator)
  if (resolved) {
    locator = resolved
  }
}

log.console("Installing " + locator + "...")

var pkg = use('package')

// Recursive install function that handles dependencies
function install_package(pkg_locator, visited) {
  if (visited[pkg_locator]) return
  visited[pkg_locator] = true
  
  // First, add to lock.toml
  shop.update(pkg_locator)
  
  // Extract/symlink the package so we can read its cell.toml
  shop.extract(pkg_locator)
  
  // Now get direct dependencies and install them first
  try {
    var deps = pkg.dependencies(pkg_locator)
    if (deps) {
      for (var alias in deps) {
        var dep_locator = deps[alias]
        log.console("Installing dependency " + dep_locator)
        install_package(dep_locator, visited)
      }
    }
  } catch (e) {
    // Package might not have dependencies or cell.toml issue
    log.console("Warning: Could not read dependencies for " + pkg_locator + ": " + e.message)
  }
  
  // Build the package after all dependencies are installed
  build.build_package(pkg_locator)
}

install_package(locator, {})
log.console("Installed " + locator)

$stop()
