// cell update [alias] - Check for updates and optionally install them

var io = use('io')
var shop = use('shop')
var http = use('http')
var toml = use('toml')
var json = use('json')
var os = use('os')

if (!io.exists('.cell/cell.toml')) {
  log.error("No cell.toml found. Run 'cell init' first.")
  $_.stop()
  return
}

var config = shop.load_config()
if (!config || !config.dependencies) {
  log.console("No dependencies to update")
  $_.stop()
  return
}

// Load lock file
var lock_path = '.cell/lock.toml'
var lock = {}
if (io.exists(lock_path)) {
  var lock_content = io.slurp(lock_path)
  lock = toml.decode(lock_content)
}
if (!lock.modules) lock.modules = {}

var updates_available = []

// Check specific dependency or all
var deps_to_check = {}
if (args.length > 0) {
  var alias = args[0]
  if (!config.dependencies[alias]) {
    log.error("Dependency '" + alias + "' not found")
    $_.stop()
    return
  }
  deps_to_check[alias] = config.dependencies[alias]
} else {
  deps_to_check = config.dependencies
}

// Check each dependency for updates
for (var alias in deps_to_check) {
  var locator = deps_to_check[alias]
  log.console("Checking " + alias + " (" + locator + ")...")
  
  // Get API URL to check commits
  var api_url = shop.get_api_url(locator)
  if (!api_url) {
    log.console("  Cannot check updates (no API support)")
    continue
  }
  
  try {
    log.console(api_url)
    var api_response = http.fetch(api_url)
    var remote_commit = shop.extract_commit_hash(locator, text(api_response))
    
    if (!remote_commit) {
      log.console("  Failed to get remote commit")
      continue
    }
    
    var local_commit = lock.modules[alias] && lock.modules[alias].commit
    
    if (!local_commit) {
      log.console("  No local commit tracked")
      updates_available.push({
        alias: alias,
        locator: locator,
        local_commit: null,
        remote_commit: remote_commit
      })
    } else if (local_commit != remote_commit) {
      log.console("  Update available!")
      log.console("    Local:  " + local_commit.substring(0, 8))
      log.console("    Remote: " + remote_commit.substring(0, 8))
      updates_available.push({
        alias: alias,
        locator: locator,
        local_commit: local_commit,
        remote_commit: remote_commit
      })
    } else {
      log.console("  Up to date (" + local_commit.substring(0, 8) + ")")
    }
  } catch (e) {
    log.console("  Failed to check: " + e)
  }
}

if (updates_available.length == 0) {
  log.console("\nAll dependencies are up to date!")
  $_.stop()
  return
}

log.console("\n" + updates_available.length + " update(s) available:")
for (var i = 0; i < updates_available.length; i++) {
  var update = updates_available[i]
  log.console("  - " + update.alias)
}

// If specific dependency was requested, auto-install
if (args.length > 0 && updates_available.length > 0) {
  log.console("\nDownloading update...")
  os.system("cell mod download")
} else if (updates_available.length > 0) {
  log.console("\nRun 'cell mod download' to install updates")
}

$_.stop()