# encoding: UTF-8
begin
  puts "###DZW-DELETE-SEL-20260920"
  m = Sketchup.active_model
  bk = 'E:/도진팩토리/3D스캔및티칭시스템/_자동화/autosave/BACKUP_before_delsel.skp'
  m.save_copy(bk)
  puts "BACKUP=#{bk}"
  sel = m.selection.to_a
  puts "선택 #{sel.length}개"
  if sel.empty?
    puts "STOP: 선택 0개 -> 변경 없음"
  else
    kinds = {}
    sel.each { |e| kinds[e.class.to_s] = (kinds[e.class.to_s] || 0) + 1 }
    puts "종류: #{kinds.inspect}"
    keepnames = ['윈치와이어_일체_20260920', '하부프레임커버', 'DJ1250-윈치받침', '조립부원판_20260919']
    protect = sel.select do |e|
      nm = (e.respond_to?(:name) ? e.name.to_s : '')
      keepnames.include?(nm)
    end
    protect.each { |e| puts "보호(삭제 제외): '#{e.name}' #{e.class}" }
    victims = sel - protect
    bb = Geom::BoundingBox.new
    victims.each { |e| bb.add(e.bounds) rescue nil }
    puts "삭제 대상 #{victims.length}개, bbox min=#{bb.min.to_a.map { |v| v.to_mm.round(1) }.inspect} max=#{bb.max.to_a.map { |v| v.to_mm.round(1) }.inspect}"
    named = victims.select { |e| e.respond_to?(:name) && !e.name.to_s.empty? }
    puts "삭제 대상 중 이름 있는 것: #{named.map { |e| e.name.to_s }.uniq.inspect}"
    if victims.empty?
      puts "STOP: 보호 대상 제외 후 삭제할 것 없음"
    else
      total = 0
      m.start_operation('선택 항목 삭제', true)
      victims.each_slice(80) do |chunk|
        live = chunk.select { |e| e.valid? }
        ent = live.first ? live.first.parent.entities : nil
        begin
          if ent && live.all? { |e| e.parent == live.first.parent }
            ent.erase_entities(live)
          else
            live.each { |e| e.erase! if e.valid? }
          end
        rescue Exception => e2
          live.each { |e| (e.erase! if e.valid?) rescue nil }
        end
        total += live.length
        puts "  배치 삭제 #{live.length}개 (누적 #{total})"
      end
      m.commit_operation
      puts "삭제 완료 총 #{total}개"
      remain = nil
      m.entities.each do |e|
        next unless e.is_a?(Sketchup::Group) || e.is_a?(Sketchup::ComponentInstance)
        remain = e if (e.respond_to?(:name) ? e.name.to_s : '') == '윈치와이어_일체_20260920'
      end
      if remain && remain.valid?
        b = remain.bounds
        puts "잔존 확인 '윈치와이어_일체_20260920' 면수=#{remain.entities.grep(Sketchup::Face).length} bbox 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}"
      else
        puts "경고: 새 와이어가 보이지 않음!"
      end
      vw = m.active_view
      cam0 = vw.camera
      begin
        c = remain && remain.valid? ? remain.bounds.center : m.bounds.center
        [['iso', Geom::Point3d.new(c.x - 1500.mm, c.y - 1800.mm, c.z + 900.mm)],
         ['wide', Geom::Point3d.new(c.x - 5000.mm, c.y - 6000.mm, c.z + 3000.mm)]].each do |tag, eye|
          vw.camera = Sketchup::Camera.new(eye, c, Geom::Vector3d.new(0, 0, 1))
          vw.zoom_extents if tag == 'wide'
          f = "E:/도진팩토리/3D스캔및티칭시스템/_자동화/inbox/_delsel_#{tag}.png"
          vw.write_image(f, 1600, 1000, true)
          puts "캡처 #{tag}=#{f} 존재=#{File.exist?(f)}"
        end
      rescue Exception => e3
        puts "캡처 실패 #{e3.message}"
      ensure
        vw.camera = cam0
      end
      ok = m.save
      puts "SAVE=#{ok.inspect} modified?=#{m.modified?.inspect}"
      puts "DONE"
    end
  end
rescue Exception => e
  puts "EXC #{e.class}: #{e.message}"
  puts e.backtrace.first(6).join(" | ")
end
nil
