# encoding: UTF-8
# 1) 보라 브라켓(SWD_07/SWD_08) 삭제  2) L브라켓 상하 반전(z미러)해 그 자리에 안착  3) 웰드너트 반대면(플랜지 하면)으로 이설
m = Sketchup.active_model
NAF=24.0; NH=13.0; NBORE=17.0
def circ(cx,cy,d,seg); (0...seg).map{|i| a=2*Math::PI*i/seg; [cx+d/2*Math.cos(a), cy+d/2*Math.sin(a)]}; end

# --- 1) 보라 브라켓 삭제 ---
m.start_operation('보라 브라켓 삭제', true)
%w[SWD_08_t6_82x208 SWD_07_t6_100x233].each do |nm|
  g = m.entities.grep(Sketchup::Group).find{|e| e.name==nm}
  if g
    b=g.bounds
    puts "삭제 #{nm} bbox x %.2f..%.2f y %.2f..%.2f z %.2f..%.2f" % [b.min.x.to_mm,b.max.x.to_mm,b.min.y.to_mm,b.max.y.to_mm,b.min.z.to_mm,b.max.z.to_mm]
    g.erase!
  else
    puts "#{nm} 없음"
  end
end
m.commit_operation
puts "삭제후 생존확인: " + %w[SWD_08_t6_82x208 SWD_07_t6_100x233].map{|nm| "#{nm}=#{!m.entities.grep(Sketchup::Group).find{|e| e.name==nm}.nil?}"}.join(', ')
m.save
puts "SAVE1 #{File.mtime(m.path)}"

# --- 2) L브라켓 z미러 + 3) 너트 재부착 ---
# A: 플랜지 목표 z 213.13~219.13 / B: 221.42~227.42  (삭제된 보라 브라켓 자세와 동일)
[['연결브라켓_L_A_20260919', 213.13, 219.13, [9048.0, 9138.0], 10908.5],
 ['연결브라켓_L_B_20260919', 221.42, 227.42, [9072.7, 9140.0], 11786.0]].each do |nm, zb, zt, hxs, hy|
  par = m.entities.grep(Sketchup::Group).find{|e| e.name==nm}
  next puts("#{nm} 없음") if par.nil?
  cz = (zt + 230.5)/2.0
  m.start_operation("#{nm} 반전·이설", true)
  par.entities.grep(Sketchup::Group).select{|g| g.name.to_s.start_with?('웰드너트')}.each{|g| g.erase!}
  par.transform!(Geom::Transformation.scaling(Geom::Point3d.new(0, 0, cz.mm), 1, 1, -1))
  rc = NAF/Math.sqrt(3.0)
  hxs.each_with_index do |hx,i|
    ng = par.entities.add_group
    ng.entities.add_face((0...6).map{|k| a=(30.0+60.0*k)*Math::PI/180.0; Geom::Point3d.new((hx+rc*Math.cos(a)).mm,(hy+rc*Math.sin(a)).mm, zb.mm)})
    bf = ng.entities.add_face(circ(hx,hy,NBORE,16).map{|x,y| Geom::Point3d.new(x.mm,y.mm,zb.mm)}); bf.erase! if bf && bf.valid?
    nf = ng.entities.grep(Sketchup::Face).max_by{|q| q.area}; nf.reverse! if nf.normal.z > 0; nf.pushpull(NH.mm)
    ng.name = "웰드너트_M16_#{nm[-13,1]}#{i+1}"
  end
  m.commit_operation
  b = par.bounds
  subs = par.entities.grep(Sketchup::Group)
  puts "#{nm} 조각solid=#{subs.map{|g| g.manifold?}.inspect} bbox x %.1f..%.1f y %.1f..%.1f z %.1f..%.1f / 플랜지 z %.2f~%.2f / 너트 z %.2f~%.2f (하면)" %
    [b.min.x.to_mm,b.max.x.to_mm,b.min.y.to_mm,b.max.y.to_mm,b.min.z.to_mm,b.max.z.to_mm, zb, zt, zb-NH, zb]
end
m.save
puts "SAVE2 #{File.mtime(m.path)} TOP=#{m.entities.count}"
nil
