# encoding: UTF-8
# L브라켓 A/B를 삭제된 보라 브라켓(SWD_08/SWD_07) 자리로 이동 + 상대면/간섭 실측
m = Sketchup.active_model
# 보라 브라켓 원위치(삭제 전 기록)
TGT = { 'A' => {:zt=>219.13, :cx=>(9018.65+9239.11)/2.0, :yo=>10950.96},
        'B' => {:zt=>227.42, :cx=>(9030.70+9263.70)/2.0, :yo=>11743.54} }

res = []
m.start_operation('L브라켓 프레임 삽입', true)
%w[A B].each do |nm|
  par = m.entities.grep(Sketchup::Group).find{|g| g.name=="연결브라켓_L_#{nm}_20260919"}
  next res << "#{nm} 없음" if par.nil?
  b = par.bounds
  dx = TGT[nm][:cx] - ((b.min.x.to_mm + b.max.x.to_mm)/2.0)
  dz = TGT[nm][:zt] - b.max.z.to_mm
  dy = 0.0
  par.transform!(Geom::Transformation.translation(Geom::Vector3d.new(dx.mm, dy.mm, dz.mm)))
  nb = par.bounds
  res << "#{nm} 이동 dx=%.2f dz=%.2f -> bbox x %.2f..%.2f y %.2f..%.2f z %.2f..%.2f" %
    [dx, dz, nb.min.x.to_mm,nb.max.x.to_mm,nb.min.y.to_mm,nb.max.y.to_mm,nb.min.z.to_mm,nb.max.z.to_mm]
end
m.commit_operation
res.each{|r| puts r}

# 상대면 실측: 플랜지 상면 평면(z=목표)에 닿는 다른 부재 면이 있는지 + 실체 간섭
%w[A B].each do |nm|
  par = m.entities.grep(Sketchup::Group).find{|g| g.name=="연결브라켓_L_#{nm}_20260919"}
  next if par.nil?
  pb = par.bounds; zt = TGT[nm][:zt]
  touch = []; over = []
  (m.entities.grep(Sketchup::Group) + m.entities.grep(Sketchup::ComponentInstance)).each do |o|
    next if o == par || o.hidden?
    ib = o.bounds.intersect(pb)
    next unless ib.valid? && ib.width.to_mm > 0.05 && ib.height.to_mm > 0.05 && ib.depth.to_mm > 0.05
    onm = o.name.to_s.empty? ? '(무명)' : o.name
    over << "#{onm}[겹침 %.1fx%.1fx%.1f z %.1f..%.1f]" % [ib.width.to_mm, ib.height.to_mm, ib.depth.to_mm, ib.min.z.to_mm, ib.max.z.to_mm]
  end
  # zt 평면에 있는 다른 부재의 수평면 찾기
  scan = nil
  scan = lambda do |ents, tr, path, d|
    ents.grep(Sketchup::Face).each do |f|
      n = f.normal.transform(tr)
      next unless n.z.abs > 0.95
      fb = Geom::BoundingBox.new; f.vertices.each{|v| fb.add(v.position.transform(tr))}
      next unless (fb.min.z.to_mm - zt).abs < 0.5
      next unless fb.max.x.to_mm > pb.min.x.to_mm && fb.min.x.to_mm < pb.max.x.to_mm
      next unless fb.max.y.to_mm > pb.min.y.to_mm && fb.min.y.to_mm < pb.max.y.to_mm
      touch << "#{path} z=%.2f x %.1f..%.1f y %.1f..%.1f" % [fb.min.z.to_mm, fb.min.x.to_mm,fb.max.x.to_mm,fb.min.y.to_mm,fb.max.y.to_mm]
    end
    return if d > 2
    (ents.grep(Sketchup::Group)+ents.grep(Sketchup::ComponentInstance)).each do |e|
      next if e == par || e.hidden?
      en = e.respond_to?(:name) && !e.name.to_s.empty? ? e.name : '(무명)'
      sub = e.is_a?(Sketchup::Group) ? e.entities : e.definition.entities
      scan.call(sub, tr * e.transformation, "#{path}/#{en}", d+1)
    end
  end
  scan.call(m.entities, Geom::Transformation.new, '', 0)
  puts "#{nm} 플랜지상면 z=#{zt} 접촉 상대면: #{touch.uniq.first(6).inspect}"
  puts "#{nm} bbox 겹침: #{over.inspect}"
end
m.save
puts "SAVED #{File.mtime(m.path)}"
nil
