// cell get <locator> - Fetch a module and add it to dependencies

var io = use('io')
var shop = use('shop')
var miniz = use('miniz')
var http = use('http')

if (args.length < 1) {
  log.console("Usage: cell get <locator> [alias]")
  log.console("Examples:")
  log.console("  cell get git.world/jj/mod@v0.6.3")
  log.console("  cell get git.world/jj/mod         (uses head/master)")
  $_.stop()
  return
}

var locator = args[0]
var parsed = shop.parse_locator(locator)

// If no version specified, append @head
if (!parsed) {
  if (locator.indexOf('@') == -1) {
    locator = locator + '@head'
    parsed = shop.parse_locator(locator)
  }
}

if (!parsed) {
  log.error("Invalid locator format. Expected: host/owner/name[@version]")
  $_.stop()
  return
}

// Initialize shop if needed
if (!io.exists('.cell/cell.toml')) {
  log.console("No cell.toml found. Initializing...")
  shop.init()
}

// Load current config
var config = shop.load_config()
if (!config) {
  log.error("Failed to load cell.toml")
  $_.stop()
  return
}

// Use the module name as the default alias
var alias = parsed.name
if (args.length > 1) {
  alias = args[1]
}

// Check if already exists
if (config.dependencies && config.dependencies[alias]) {
  log.console("Dependency '" + alias + "' already exists with version: " + config.dependencies[alias])
  log.console("Use 'cell update " + alias + "' to change version")
  $_.stop()
  return
}

// Add to dependencies
log.console("Adding dependency: " + alias + " = " + locator)
shop.add_dependency(alias, locator)

// Create module directory
var module_dir = '.cell/modules/' + alias + '@' + parsed.version
if (!io.exists(module_dir)) {
  io.mkdir(module_dir)
}

// TODO: Actually fetch the module from the repository
log.console("Module directory created at: " + module_dir)
log.console("TODO: Implement actual fetching from " + parsed.path)
log.console("")
log.console("For now, manually place module files in: " + module_dir)
log.console("Then run 'cell build' to compile modules")

// Update lock.toml
// TODO: Calculate and store checksums

$_.stop()