# encoding: UTF-8
# fix1 — 주황판 9.4mm 상승(겹침 해소) + 사이드막음판 A/B 에서 흰판 관통부 노치(subtract)
HB = 'E:/도진팩토리/3D스캔및티칭시스템/_자동화/inbox/_보류/_fix1_heartbeat.txt'
def hb(s); begin; File.open(HB,'a:UTF-8'){|f| f.write("[#{Time.now.strftime('%H:%M:%S')}] #{s}\n"); f.flush}; rescue Exception; end; end
MM = 25.4
m = Sketchup.active_model
out = []
hb("START")
g2 = m.entities.grep(Sketchup::Group).find { |g| g.definition.name == "그룹#2" }
s04 = g2.entities.grep(Sketchup::Group).find { |g| g.name == "SWD_04_t9_240x1046" }
won = m.entities.grep(Sketchup::Group).find { |g| g.name == "조립부원판_20260919" }
sides = ["사이드막음판_9T_A_20260919", "사이드막음판_9T_B_20260919"].map { |n| m.entities.grep(Sketchup::Group).find { |g| g.name == n } }
if [s04, won].any?(&:nil?) || sides.any?(&:nil?)
  out << "대상 없음 -> 중단"; hb("ABORT")
else
  lift = 9.4
  begin
    base = File.basename(m.path,'.skp'); dir = File.dirname(m.path)
    m.save_copy(File.join(dir, "#{base}.bak_#{Time.now.strftime('%Y%m%d_%H%M%S')}_fix1직전.skp"))
    hb("BACKUP OK")
    m.start_operation("겹침 해소: 주황판 상승 + 사이드판 노치", true)
    tw = Geom::Transformation.translation(Geom::Vector3d.new(0, 0, lift / MM))
    s04.transformation = g2.transformation.inverse * tw * g2.transformation * s04.transformation
    hb("LIFT")
    newsides = []
    sides.each do |sp|
      nm = sp.name
      wc = m.entities.add_group
      wc.entities.add_instance(won.definition, won.transformation).explode
      if wc.manifold?
        r = wc.subtract(sp)   # SketchUp: a.subtract(b) = b - a
        if r
          r.name = nm
          newsides << r
          hb("NOTCH #{nm} solid=#{r.manifold?}")
        else
          out << "#{nm}: subtract 실패"
        end
      else
        wc.erase!
        out << "#{nm}: 흰판 복제 실패"
      end
    end
    m.commit_operation
    hb("COMMIT")
    wb = Geom::BoundingBox.new
    [s04.bounds.min, s04.bounds.max].each { |p| wb.add(p.transform(g2.transformation)) }
    out << "주황판 상승 #{lift}mm -> z #{(wb.min.z*25.4).round(2)}..#{(wb.max.z*25.4).round(2)} (수평 유지)"
    newsides.each do |g|
      b = g.bounds
      out << "#{g.name}: 노치 후 z #{(b.min.z*25.4).round(2)}..#{(b.max.z*25.4).round(2)} y #{(b.min.y*25.4).round(2)}..#{(b.max.y*25.4).round(2)} solid=#{g.manifold?}"
    end
  rescue Exception => e
    m.commit_operation rescue nil
    out << "ERR #{e.class}: #{e.message}"; hb("ERR #{e.message}")
  end
end
puts out.join("\n")
hb("END")
"FIX1"
