# encoding: UTF-8
begin
  puts "###DZW-SCAN-INSERT2-20260920"
  m = Sketchup.active_model
  sel = m.selection.to_a
  if sel.empty?
    puts "STOP: 선택 0개"
  else
    f = lambda { |b| "min=#{b.min.to_a.map { |v| v.to_mm.round(1) }.inspect} max=#{b.max.to_a.map { |v| v.to_mm.round(1) }.inspect}" }
    ub = Geom::BoundingBox.new
    puts "선택 #{sel.length}개"
    sel.each_with_index do |e, i|
      nm = (e.respond_to?(:name) ? e.name.to_s : '')
      dn = (e.is_a?(Sketchup::ComponentInstance) ? e.definition.name.to_s : '')
      ub.add(e.bounds)
      tr = e.respond_to?(:transformation) ? e.transformation : nil
      puts "  SEL[#{i}] #{e.class} name='#{nm}' def='#{dn}' #{f.call(e.bounds)}"
      puts "        원점=#{tr.origin.to_a.map { |v| v.to_mm.round(1) }.inspect} scale=[#{tr.xscale.round(4)},#{tr.yscale.round(4)},#{tr.zscale.round(4)}]" if tr
    end
    puts "선택 전체 #{f.call(ub)}"
    ctr = ub.center
    nb = []
    m.active_entities.each do |e|
      next unless e.is_a?(Sketchup::Group) || e.is_a?(Sketchup::ComponentInstance)
      next if sel.include?(e)
      d = e.bounds.center.distance(ctr).to_mm
      nm = (e.respond_to?(:name) ? e.name.to_s : '')
      nm = e.definition.name.to_s if nm.empty? && e.is_a?(Sketchup::ComponentInstance)
      nb << [d, "  NB d=#{d.round(1)} '#{nm}' #{e.class} #{f.call(e.bounds)}"]
    end
    nb.sort_by! { |a| a[0] }
    puts "가까운 이웃 20개 (총 #{nb.length}):"
    nb.first(20).each { |a| puts a[1] }
  end
rescue Exception => e
  puts "EXC #{e.class}: #{e.message}"
end
nil
