# encoding: UTF-8
begin
  puts "###DZW-UNDO-COVEROUTER-20260920"
  m = Sketchup.active_model
  cov = nil
  m.active_entities.each do |e|
    next unless e.is_a?(Sketchup::Group) || e.is_a?(Sketchup::ComponentInstance)
    cov = e if (e.respond_to?(:name) ? e.name.to_s : '') == '하부프레임커버'
  end
  if cov.nil?
    puts "STOP: 커버 미발견"
  else
    b = cov.bounds
    puts "UNDO 전 커버 Y=[#{b.min.y.to_mm.round(1)},#{b.max.y.to_mm.round(1)}] 폭=#{(b.max.y.to_mm - b.min.y.to_mm).round(1)}"
    Sketchup.send_action('editUndo:')
    UI.start_timer(1.0, false) do
      begin
        c2 = nil
        m.active_entities.each do |e|
          next unless e.is_a?(Sketchup::Group) || e.is_a?(Sketchup::ComponentInstance)
          c2 = e if (e.respond_to?(:name) ? e.name.to_s : '') == '하부프레임커버'
        end
        d = 'E:/도진팩토리/3D스캔및티칭시스템/_자동화/inbox'
        txt = ''
        if c2
          bb = c2.bounds
          w = bb.max.y.to_mm - bb.min.y.to_mm
          txt << "[UNDO확인] 커버 Y=[#{bb.min.y.to_mm.round(1)},#{bb.max.y.to_mm.round(1)}] 폭=#{w.round(1)} (정상=1294.2)\n"
          txt << "[UNDO확인] 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}\n"
          if (w - 1294.2).abs < 1.0
            ok = m.save
            txt << "[UNDO확인] 복구 정상 -> SAVE=#{ok.inspect} modified?=#{m.modified?.inspect}\n"
          else
            txt << "[UNDO확인] 폭 불일치 -> 저장하지 않음. 백업 파일 사용 필요: BACKUP_before_coverouter.skp\n"
          end
        else
          txt << "[UNDO확인] 커버 미발견\n"
        end
        File.open(File.join(d, '_result.txt'), 'a:UTF-8') { |f| f.write(txt) }
      rescue Exception => e2
        File.open('E:/도진팩토리/3D스캔및티칭시스템/_자동화/inbox/_result.txt', 'a:UTF-8') { |f| f.write("[UNDO확인] EXC #{e2.class}: #{e2.message}\n") }
      end
    end
    puts "UNDO 실행 요청 완료(1초 후 확인 기록)"
  end
rescue Exception => e
  puts "EXC #{e.class}: #{e.message}"
end
nil
