// cell index <file> — Build semantic index for a source file.
//
// Usage:
//   cell index <file.ce|file.cm>         Index one file, output JSON to stdout
//   cell index <file> -o <output.json>   Index one file, write to file
//   cell index --help                    Show this help

var fd = use('fd')
var json = use('json')
var tokenize_mod = use('tokenize')
var parse_mod = use('parse')
var fold_mod = use('fold')
var index_mod = use('index')
var shop = use('internal/shop')

var filename = null
var output_path = null
var i = 0
var file_info = null
var pkg_ctx = null
var resolved = null
var local_path = null

for (i = 0; i < length(args); i++) {
  if (args[i] == '-o' || args[i] == '--output') {
    if (i + 1 < length(args)) {
      output_path = args[i + 1]
      i = i + 1
    } else {
      log.error('-o requires a file path')
      $stop()
    }
  } else if (args[i] == '--help' || args[i] == '-h') {
    log.console("Usage: cell index <file.ce|file.cm> [options]")
    log.console("")
    log.console("Build a semantic index for a source file.")
    log.console("")
    log.console("Options:")
    log.console("  -o <path>   Write output to file instead of stdout")
    $stop()
  } else if (!starts_with(args[i], '-')) {
    filename = args[i]
  }
}

if (filename == null) {
  log.error('No file specified. Usage: cell index <file>')
  $stop()
}

if (!fd.is_file(filename)) {
  log.error('File not found: ' + filename)
  $stop()
}

var src = text(fd.slurp(filename))
var pipeline = {tokenize: tokenize_mod, parse: parse_mod, fold: fold_mod}
var idx = index_mod.index_file(src, filename, pipeline)

// Resolve import paths to filesystem locations.
file_info = shop.file_info(fd.realpath(filename))
pkg_ctx = file_info.package
i = 0
while (i < length(idx.imports)) {
  resolved = shop.resolve_use_path(idx.imports[i].module_path, pkg_ctx)
  // Fallback: check sibling files in the same directory.
  if (resolved == null) {
    local_path = fd.dirname(fd.realpath(filename)) + '/' + idx.imports[i].module_path + '.cm'
    if (fd.is_file(local_path)) {
      resolved = local_path
    }
  }
  if (resolved != null) {
    idx.imports[i].resolved_path = resolved
  }
  i = i + 1
}

var out = json.encode(idx, true)

if (output_path != null) {
  fd.slurpwrite(output_path, out)
  log.console('Wrote index to ' + output_path)
} else {
  print(out)
  print("\n")
}

$stop()
