// cell build [<locator>] - Build dynamic libraries locally for the current machine
//
// Usage:
//   cell build                Build dynamic libraries for all packages in shop
//   cell build .              Build dynamic library for current directory package
//   cell build <locator>      Build dynamic library for specific package
//   cell build -t <target>    Cross-compile dynamic libraries for target platform
//   cell build -b <type>      Build type: release (default), debug, or minsize
//   cell build --verbose      Print resolved flags, commands, and cache status

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

var target = null
var target_package = null
var buildtype = 'release'
var verbose = false
var force_rebuild = false
var dry_run = false
var i = 0
var targets = null
var t = 0
var lib = null
var results = null
var success = 0
var failed = 0

var run = function() {
  for (i = 0; i < length(args); i++) {
    if (args[i] == '-t' || args[i] == '--target') {
      if (i + 1 < length(args)) {
        target = args[++i]
      } else {
        log.error('-t requires a target')
        return
      }
    } else if (args[i] == '-p' || args[i] == '--package') {
      // Legacy support for -p flag
      if (i + 1 < length(args)) {
        target_package = args[++i]
      } else {
        log.error('-p requires a package name')
        return
      }
    } else if (args[i] == '-b' || args[i] == '--buildtype') {
      if (i + 1 < length(args)) {
        buildtype = args[++i]
        if (buildtype != 'release' && buildtype != 'debug' && buildtype != 'minsize') {
          log.error('Invalid buildtype: ' + buildtype + '. Must be release, debug, or minsize')
          return
        }
      } else {
        log.error('-b requires a buildtype (release, debug, minsize)')
        return
      }
    } else if (args[i] == '--force') {
      force_rebuild = true
    } else if (args[i] == '--verbose' || args[i] == '-v') {
      verbose = true
    } else if (args[i] == '--dry-run') {
      dry_run = true
    } else if (args[i] == '--list-targets') {
      log.console('Available targets:')
      targets = build.list_targets()
      for (t = 0; t < length(targets); t++) {
        log.console('  ' + targets[t])
      }
      return
    } else if (!starts_with(args[i], '-') && !target_package) {
      // Positional argument - treat as package locator
      target_package = args[i]
    }
  }

if (target_package)
  target_package = shop.resolve_locator(target_package)

// Detect target if not specified
if (!target) {
  target = build.detect_host_target()
  if (target) log.console('Target: ' + target)
}

  if (target && !build.has_target(target)) {
    log.error('Invalid target: ' + target)
    log.console('Available targets: ' + text(build.list_targets(), ', '))
    return
  }

var packages = shop.list_packages()
arrfor(packages, function(package) {
  if (package == 'core') return
  shop.sync(package, {no_build: true})
})

var _build = null
if (target_package) {
  // Build single package
  log.console('Building ' + target_package + '...')
  _build = function() {
    lib = build.build_dynamic(target_package, target, buildtype, {verbose: verbose, force: force_rebuild})
    if (lib) {
      log.console(`Built ${text(length(lib))} module(s)`)
    }
  } disruption {
    log.error('Build failed')
    $stop()
  }
  _build()
} else {
  // Build all packages
  log.console('Building all packages...')
  results = build.build_all_dynamic(target, buildtype, {verbose: verbose, force: force_rebuild})

  success = 0
  failed = 0
  for (i = 0; i < length(results); i++) {
    if (results[i].modules) {
      success = success + length(results[i].modules)
    }
  }

  log.console(`Build complete: ${success} libraries built${failed > 0 ? `, ${failed} failed` : ''}`)
}
}
run()

$stop()
