# encoding: UTF-8
# trim1 — 격판에서 주황판 실체를 빼서 간섭 0 보장 (a.subtract(b) = b - a)
HB = 'E:/도진팩토리/3D스캔및티칭시스템/_자동화/inbox/_보류/_trim_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
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" }
names = ["SWD_02_jog30_6T_20260919", "SWD_03_jog20_6T_20260919"]
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')}_trim직전.skp"))
  hb("BACKUP OK")
  m.start_operation("격판 주황판 간섭 트림", true)
  names.each do |nm|
    p = m.entities.grep(Sketchup::Group).find { |g| g.name == nm }
    next if p.nil?
    oc = m.entities.add_group
    oc.entities.add_instance(s04.definition, g2.transformation * s04.transformation).explode
    if oc.manifold?
      r = oc.subtract(p)
      if r
        r.name = nm
        b = r.bounds
        out << "#{nm}: 트림 후 z #{(b.min.z*25.4).round(2)}..#{(b.max.z*25.4).round(2)} solid=#{r.manifold?}"
        hb("TRIM #{nm}")
      else
        out << "#{nm}: subtract nil"
      end
    else
      oc.erase!
      out << "#{nm}: 주황판 복제 실패"
    end
  end
  m.commit_operation
  hb("COMMIT")
rescue Exception => e
  m.commit_operation rescue nil
  out << "ERR #{e.class}: #{e.message}"; hb("ERR #{e.message}")
end
puts out.join("\n")
hb("END")
"TRIM1"
