# encoding: UTF-8
# fixall — ① 사이드판A 재생성(비솔리드 복구) ② 주황판 0.5mm 추가 상승 ③ 사이드판·격판 트림
HB = 'E:/도진팩토리/3D스캔및티칭시스템/_자동화/inbox/_보류/_fixall_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
    nil
  end
end
MM = 25.4
def vol(g); (g.volume rescue -1) * (25.4**3); 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" }
won = m.entities.grep(Sketchup::Group).find { |g| g.name == "조립부원판_20260919" }
pa = m.entities.grep(Sketchup::Group).find { |g| g.name == "사이드막음판_9T_A_20260919" }
pb = m.entities.grep(Sketchup::Group).find { |g| g.name == "사이드막음판_9T_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')}_fixall직전.skp"))
  hb("BACKUP OK")
  m.start_operation("사이드판A 복구 + 주황판 미세상승 + 트림", true)

  # ① 주황판 0.5mm 상승 (하판 22.8mm3 관통 해소)
  tw = Geom::Transformation.translation(Geom::Vector3d.new(0, 0, 0.5 / MM))
  s04.transformation = g2.transformation.inverse * tw * g2.transformation * s04.transformation
  hb("LIFT 0.5")

  # ② 사이드판 A 재생성: B(정상 솔리드)의 거울상으로 (CEO 외곽 동일)
  ymid = 11376.055
  fb = pb.entities.grep(Sketchup::Face).select { |f| f.normal.y.abs > 0.9 }.max_by { |f| f.area }
  pts = fb.vertices.map { |v| v.position.transform(pb.transformation) }
  mir = pts.map { |p| Geom::Point3d.new(p.x, (2 * ymid / 25.4) - p.y, p.z) }
  pa.erase! if pa
  na = m.entities.add_group
  f = na.entities.add_face(mir)
  f.pushpull(f.normal.y > 0 ? 9.0 / MM : -9.0 / MM)
  na.name = "사이드막음판_9T_A_20260919"
  b0 = na.bounds
  # 위치 보정: 안쪽면이 y=10879.34 가 되도록
  dy = 10879.34 - (b0.max.y * 25.4)
  na.transform!(Geom::Transformation.translation(Geom::Vector3d.new(0, dy / MM, 0)))
  hb("REBUILD A solid=#{na.manifold?} dy=#{dy.round(3)}")
  out << "사이드판A 재생성(B 거울상): solid=#{na.manifold?} 체적 #{vol(na).round(0)}mm3 이동보정 #{dy.round(3)}mm"

  m.commit_operation
  hb("COMMIT1")
rescue Exception => e
  m.commit_operation rescue nil
  out << "ERR1 #{e.class}: #{e.message}"
  hb("ERR1 #{e.message}")
end

# ③ 트림: 사이드판 A/B 에서 하판 제거, 격판에서 주황판 제거
begin
  m.start_operation("겹침 트림", true)
  [["사이드막음판_9T_A_20260919", won, nil], ["사이드막음판_9T_B_20260919", won, nil],
   ["SWD_02_jog30_6T_20260919", s04, g2.transformation], ["SWD_03_jog20_6T_20260919", s04, g2.transformation]].each do |nm, cutter, pre|
    tgt = m.entities.grep(Sketchup::Group).find { |g| g.name == nm }
    next if tgt.nil?
    v0 = vol(tgt)
    cc = m.entities.add_group
    tr = pre ? (pre * cutter.transformation) : cutter.transformation
    cc.entities.add_instance(cutter.definition, tr).explode
    if cc.manifold?
      r = cc.subtract(tgt)
      if r
        r.name = nm
        out << "#{nm}: 트림 #{v0.round(0)} -> #{vol(r).round(0)}mm3 (제거 #{(v0 - vol(r)).round(0)}), solid=#{r.manifold?}"
      else
        out << "#{nm}: 겹침 없음(subtract nil), 체적 #{v0.round(0)}mm3 유지"
      end
    else
      cc.erase!
      out << "#{nm}: 커터 비솔리드"
    end
    hb("TRIM #{nm}")
  end
  m.commit_operation
  hb("COMMIT2")
rescue Exception => e
  m.commit_operation rescue nil
  out << "ERR2 #{e.class}: #{e.message}"
end
puts out.join("\n")
hb("END")
"FIXALL"
