# encoding: UTF-8
# r8 — ① 하판 앞쪽(y<10731.8) 잔재 제거 ② 능선 2줄을 하판 하면에 완전 밀착(0.561mm 상승)
HB = 'E:/도진팩토리/3D스캔및티칭시스템/_자동화/inbox/_보류/_r8_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
def vol(g); (g.volume rescue -1) * 16387.064; end
def boxgrp(ents, x0, x1, y0, y1, z0, z1)
  g = ents.add_group
  f = g.entities.add_face([Geom::Point3d.new(x0/25.4,y0/25.4,z0/25.4), Geom::Point3d.new(x1/25.4,y0/25.4,z0/25.4),
                           Geom::Point3d.new(x1/25.4,y1/25.4,z0/25.4), Geom::Point3d.new(x0/25.4,y1/25.4,z0/25.4)])
  f.reverse! if f.normal.z < 0
  f.pushpull((z1-z0)/25.4)
  g
end
m = Sketchup.active_model
out = []
hb("START")
plate = m.entities.grep(Sketchup::Group).find { |g| g.name == "조립부원판_20260919" }
ra = m.entities.grep(Sketchup::Group).find { |g| g.name == "보강능선_6T_A_20260919" }
rb = m.entities.grep(Sketchup::Group).find { |g| g.name == "보강능선_6T_B_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')}_r8직전.skp"))
  hb("BACKUP OK")
  m.start_operation("하판 잔재 정리 + 능선 밀착", true)
  v0 = vol(plate)
  cb = boxgrp(m.entities, 8700.0, 9320.0, 9900.0, 10731.0, -300.0, 300.0)
  r = cb.subtract(plate)
  body = r || plate
  body.name = "조립부원판_20260919"
  out << "하판 앞쪽 잔재 제거: 체적 #{v0.round(0)} -> #{vol(body).round(0)}mm3, bbox y #{(body.bounds.min.y*25.4).round(1)}..#{(body.bounds.max.y*25.4).round(1)} solid=#{body.manifold?}"
  [ra, rb].each do |g|
    next if g.nil?
    g.transform!(Geom::Transformation.translation(Geom::Vector3d.new(0, 0, 0.561/MM)))
  end
  m.commit_operation
  hb("COMMIT")
  [ra, rb].each do |g|
    next if g.nil?
    b = g.bounds
    out << "#{g.name}: 상단 z #{(b.max.z*25.4).round(3)} (0.561mm 상승 적용), y #{(b.min.y*25.4).round(1)}..#{(b.max.y*25.4).round(1)}, solid=#{g.manifold?}, 체적 #{vol(g).round(0)}mm3"
  end
rescue Exception => e
  m.commit_operation rescue nil
  out << "ERR #{e.class}: #{e.message}"
  hb("ERR #{e.message}")
end
v = m.active_view
v.camera = Sketchup::Camera.new(Geom::Point3d.new(8450/25.4, 10350/25.4, -260/25.4), Geom::Point3d.new(9040/25.4, 11380/25.4, 95/25.4), Geom::Vector3d.new(0,0,1))
out << "capture=#{v.write_image('E:/도진팩토리/3D스캔및티칭시스템/_자동화/inbox/_보류/_capR8.png', 1400, 900, true)}"
puts out.join("\n")
hb("END")
"R8"
