// cell audit [<locator>] - Test-compile all .ce and .cm scripts
//
// Usage:
//   cell audit              Audit all packages
//   cell audit <locator>    Audit specific package
//   cell audit .            Audit current directory package
//
// Compiles every script in the package(s) to check for errors.
// Continues past failures and reports all issues at the end.

var shop = use('internal/shop')
var pkg = use('package')

var target_package = null
var i = 0

var run = function() {
  for (i = 0; i < length(args); i++) {
    if (args[i] == '--help' || args[i] == '-h') {
      log.console("Usage: cell audit [<locator>]")
      log.console("")
      log.console("Test-compile all .ce and .cm scripts in package(s).")
      log.console("Reports all errors without stopping at the first failure.")
      return
    } else if (!starts_with(args[i], '-')) {
      target_package = args[i]
    }
  }

// Resolve local paths
if (target_package) {
  target_package = shop.resolve_locator(target_package)
}

var packages = null
var total_ok = 0
var total_errors = 0
var total_scripts = 0
var all_failures = []
var all_unresolved = []

if (target_package) {
  packages = [target_package]
} else {
  packages = shop.list_packages()
}

arrfor(packages, function(p) {
  var scripts = shop.get_package_scripts(p)
  if (length(scripts) == 0) return

  log.console("Auditing " + p + " (" + text(length(scripts)) + " scripts)...")
  var result = shop.build_package_scripts(p)
  total_ok = total_ok + result.ok
  total_errors = total_errors + length(result.errors)
  total_scripts = total_scripts + result.total

  arrfor(result.errors, function(e) {
    push(all_failures, p + ": " + e)
  })

  // Check use() resolution
  var resolution = shop.audit_use_resolution(p)
  arrfor(resolution.unresolved, function(u) {
    push(all_unresolved, p + '/' + u.script + ": use('" + u.module + "') cannot be resolved")
  })
})

log.console("")
if (length(all_failures) > 0) {
  log.console("Failed scripts:")
  arrfor(all_failures, function(f) {
    log.console("  " + f)
  })
  log.console("")
}

if (length(all_unresolved) > 0) {
  log.console("Unresolved modules:")
  arrfor(all_unresolved, function(u) {
    log.console("  " + u)
  })
  log.console("")
}

var summary = "Audit complete: " + text(total_ok) + "/" + text(total_scripts) + " scripts compiled"
if (total_errors > 0) summary = summary + ", " + text(total_errors) + " failed"
if (length(all_unresolved) > 0) summary = summary + ", " + text(length(all_unresolved)) + " unresolved use() calls"
log.console(summary)
}
run()

$stop()
