// cell query — Semantic queries across packages.
//
// Usage:
//   cell query --this [--top|--fn] [<package>]   this references
//   cell query --intrinsic <name> [<package>]    Find built-in intrinsic usage
//   cell query --decl <name> [<package>]         Variable declarations by name
//   cell query --help                            Show usage

var shop = use('internal/shop')
var query_mod = use('query')
var fd = use('fd')

var mode = null
var name = null
var this_scope = null
var pkg_filter = null
var show_help = false
var i = 0

for (i = 0; i < length(args); i++) {
  if (args[i] == '--this') {
    mode = "this"
  } else if (args[i] == '--top') {
    this_scope = "top"
  } else if (args[i] == '--fn') {
    this_scope = "fn"
  } else if (args[i] == '--intrinsic') {
    mode = "intrinsic"
    if (i + 1 < length(args) && !starts_with(args[i + 1], '-')) {
      name = args[i + 1]
      i = i + 1
    } else {
      log.error('--intrinsic requires a name')
      mode = "error"
    }
  } else if (args[i] == '--decl') {
    mode = "decl"
    if (i + 1 < length(args) && !starts_with(args[i + 1], '-')) {
      name = args[i + 1]
      i = i + 1
    } else {
      log.error('--decl requires a name')
      mode = "error"
    }
  } else if (args[i] == '--help' || args[i] == '-h') {
    show_help = true
  } else if (!starts_with(args[i], '-')) {
    pkg_filter = args[i]
  }
}

var all_files = null
var files = []
var j = 0
var idx = null
var hits = null
var hit = null
var k = 0

// Use return pattern to avoid closure-over-object issue with disruption.
var safe_index = function(path) {
  return shop.index_file(path)
} disruption {
  return null
}

if (show_help) {
  log.console("Usage: cell query [options] [<package>]")
  log.console("")
  log.console("Semantic queries across packages.")
  log.console("")
  log.console("Options:")
  log.console("  --this               All this references")
  log.console("  --this --top         Top-level this only (not inside functions)")
  log.console("  --this --fn          this inside functions only")
  log.console("  --intrinsic <name>   Find built-in intrinsic usage (e.g., print)")
  log.console("  --decl <name>        Variable declarations by name")
  log.console("")
  log.console("Without a package argument, searches all installed packages.")
} else if (mode == null || mode == "error") {
  if (mode != "error") {
    log.error('Specify --this, --intrinsic, or --decl. Use --help for usage.')
  }
} else {
  all_files = shop.all_script_paths()

  if (pkg_filter != null) {
    for (j = 0; j < length(all_files); j++) {
      if (all_files[j].package == pkg_filter) {
        files[] = all_files[j]
      }
    }
  } else {
    files = all_files
  }

  for (j = 0; j < length(files); j++) {
    idx = safe_index(files[j].full_path)
    if (idx == null) continue

    hits = null
    if (mode == "this") {
      hits = query_mod.find_this(idx, this_scope)
    } else if (mode == "intrinsic") {
      hits = query_mod.intrinsic(idx, name)
    } else if (mode == "decl") {
      hits = query_mod.find_decl(idx, name, null)
    }

    if (hits != null && length(hits) > 0) {
      for (k = 0; k < length(hits); k++) {
        hit = hits[k]
        if (hit.span != null) {
          log.console(`${files[j].package}:${files[j].rel_path}:${text(hit.span.from_row)}:${text(hit.span.from_col)}: ${hit.name}`)
        } else if (hit.decl_span != null) {
          log.console(`${files[j].package}:${files[j].rel_path}:${text(hit.decl_span.from_row)}:${text(hit.decl_span.from_col)}: ${hit.kind} ${hit.name}`)
        }
      }
    }
  }
}

$stop()
