# encoding: UTF-8
begin
  puts "###DZW-GROUP-LOWERFRAMECOVER-20260919"
  m = Sketchup.active_model
  want = 'E:/VLA시스템/에버다임/광산기계/락드릴/프레임/E500PRO-R_프레임/500PRO_R 20260917 수정안.skp'
  got  = m.path.to_s.tr("\\", "/")
  if got.downcase != want.downcase
    puts "STOP: 열린 파일 불일치"
    puts "  열림: #{got}"
    puts "  대상: #{want}"
    next_step = nil
  else
    sel = m.selection.to_a
    if sel.empty?
      puts "STOP: 선택 0개"
    else
      puts "선택 개수: #{sel.length}"
      bad = sel.reject { |e| e.is_a?(Sketchup::Group) || e.is_a?(Sketchup::ComponentInstance) }
      ub = Geom::BoundingBox.new
      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 : '')
        b = e.bounds
        ub.add(b)
        puts "  [#{i}] #{e.class} name='#{nm}' def='#{dn}' c=#{b.center.to_a.map { |v| v.to_mm.round(1) }.inspect} whd=#{[b.width.to_mm.round(1), b.height.to_mm.round(1), b.depth.to_mm.round(1)].inspect}"
      end
      puts "선택 전체 bbox c=#{ub.center.to_a.map { |v| v.to_mm.round(1) }.inspect} whd=#{[ub.width.to_mm.round(1), ub.height.to_mm.round(1), ub.depth.to_mm.round(1)].inspect}"
      if !bad.empty?
        puts "STOP: 그룹/컴포넌트가 아닌 엔티티 포함 -> #{bad.map { |e| e.class.to_s }.uniq.inspect}"
      else
        m.start_operation('하부프레임커버 그룹화', true)
        grp = m.active_entities.add_group(sel)
        grp.name = '하부프레임커버'
        m.commit_operation
        gb = grp.bounds
        puts "그룹 bbox c=#{gb.center.to_a.map { |v| v.to_mm.round(1) }.inspect} whd=#{[gb.width.to_mm.round(1), gb.height.to_mm.round(1), gb.depth.to_mm.round(1)].inspect}"
        puts "그룹 이름='#{grp.name}' 자식수=#{grp.entities.length}"
        ok = m.save
        puts "SAVE=#{ok.inspect} modified?=#{m.modified?.inspect}"
        puts "DONE"
      end
    end
  end
rescue Exception => e
  puts "EXC #{e.class}: #{e.message}"
end
nil
