require "../crystal/index/index"
require "../crystal/workspace_analyzer"

module Lattice
  module CLI
    # Prints a count of classes, modules, methods, constants, and macros found
    # in the workspace index. Scans all `.cr` files under the current directory
    # (or the path given as the first argument) using `WorkspaceIndex`.
    class Stats
      KINDS = %w[class module struct enum lib method property instance_variable constant macro]

      def self.run(args : Array(String)) : NoReturn
        root = args.first? || Dir.current

        unless Dir.exists?(root)
          STDERR.puts "lattice stats: directory not found: #{root}"
          exit 1
        end

        index = Index::WorkspaceIndex.new(root)

        Dir.glob(File.join(root, "**", "*.cr")).sort.each do |file|
          next if file.includes?(".lattice-cache")
          source = File.read(file)
          index.index_file(file, source)
        rescue ex
          STDERR.puts "lattice stats: warning: could not read #{file}: #{ex.message}"
        end

        puts "Symbol counts for: #{root}"
        puts "-" * 40

        total = 0
        KINDS.each do |kind|
          count = index.all_of_kind(kind).size
          next if count == 0
          puts "  %-20s %d" % [kind, count]
          total += count
        end

        puts "-" * 40
        puts "  %-20s %d" % ["total", total]
        exit 0
      end
    end
  end
end
