// cell fetch - Fetch package zips from remote sources
//
// This command ensures that the zip files on disk match what's in the lock file.
// For local packages, this is a no-op.
// For remote packages, downloads the zip if not present or hash mismatch.
//
// Usage:
//   cell fetch           - Fetch all packages
//   cell fetch <package> - Fetch a specific package

var shop = use('internal/shop')

// Parse arguments
var target_pkg = null
var i = 0

for (i = 0; i < length(args); i++) {
  if (args[i] == '--help' || args[i] == '-h') {
    log.console("Usage: cell fetch [package]")
    log.console("Fetch package zips from remote sources.")
    log.console("")
    log.console("Arguments:")
    log.console("  package  Optional package name to fetch. If omitted, fetches all.")
    log.console("")
    log.console("This command ensures that the zip files on disk match what's in")
    log.console("the lock file. For local packages, this is a no-op.")
    $stop()
  } else if (!starts_with(args[i], '-')) {
    target_pkg = args[i]
  }
}

var all_packages = shop.list_packages()
var lock = shop.load_lock()
var packages_to_fetch = []

if (target_pkg) {
  // Fetch specific package
  if (find(all_packages, target_pkg) == null) {
    log.error("Package not found: " + target_pkg)
    $stop()
  }
  push(packages_to_fetch, target_pkg)
} else {
  // Fetch all packages
  packages_to_fetch = all_packages
}

var remote_count = 0
arrfor(packages_to_fetch, function(pkg) {
  var entry = lock[pkg]
  if (pkg != 'core' && (!entry || entry.type != 'local'))
    remote_count++
}, null, null)

if (remote_count > 0)
  log.console(`Fetching ${text(remote_count)} remote package(s)...`)

var downloaded_count = 0
var cached_count = 0
var fail_count = 0

arrfor(packages_to_fetch, function(pkg) {
  // Skip core (handled separately)
  if (pkg == 'core') return

  var result = shop.fetch(pkg)
  if (result.status == 'local') {
    // Local packages are just symlinks, nothing to fetch
    return
  } else if (result.status == 'cached') {
    cached_count++
  } else if (result.status == 'downloaded') {
    log.console("  Downloaded: " + pkg)
    downloaded_count++
  } else if (result.status == 'error') {
    log.error("  Failed: " + pkg + (result.message ? " - " + result.message : ""))
    fail_count++
  }
}, null, null)

log.console("")
var parts = []
if (downloaded_count > 0) push(parts, `${text(downloaded_count)} downloaded`)
if (cached_count > 0) push(parts, `${text(cached_count)} cached`)
if (fail_count > 0) push(parts, `${text(fail_count)} failed`)
if (length(parts) == 0) push(parts, "nothing to fetch")
log.console("Fetch complete: " + text(parts, ", "))

$stop()
