require "./inspection"

module Lattice
  module Inspections
    # Flags `require` statements whose path has already been required earlier
    # in the same file.
    #
    # Detection strategy: scan source lines from top to bottom, collecting
    # require paths.  When a path is seen for the second time, emit a warning
    # at that line.  No AST walk is needed — the check is a pure line scan.
    #
    # Code action: "Remove duplicate require"
    class RedundantRequireInspection < Inspection
      # Match both `require "path"` and `require 'path'`.
      REQUIRE_RE = /^\s*require\s+["']([^"']+)["']/

      def run(
        uri : String,
        source : String,
        lines : Array(String),
        ast : ::Crystal::ASTNode,
      ) : Array(::LSP::Diagnostic)
        diagnostics = [] of ::LSP::Diagnostic
        seen = Set(String).new

        lines.each_with_index do |line, ln|
          m = line.match(REQUIRE_RE)
          next unless m

          path = m[1]
          if seen.includes?(path)
            col_start = (line.index("require") || 0)
            col_end   = line.rstrip.size
            diagnostics << diagnostic(
              "Redundant require: \"#{path}\" is already required earlier in this file",
              ln,
              col_start,
              ln,
              col_end,
              ::LSP::DiagnosticSeverity::Warning,
              "lattice",
            )
          else
            seen.add(path)
          end
        end

        diagnostics
      end
    end
  end
end
