# encoding: UTF-8
m = Sketchup.active_model
MM = 1.0/25.4
mL, xL0, zL0 = 0.1129672, 4423.8, 20.4
cL = 1.0/Math.sqrt(1+mL*mL)
u = lambda{|x| (x-xL0)/cL}
X0, X1 = 3940.0, 4410.0
U0, U1 = u.call(X0), u.call(X1)
T, H = 12.0, 100.0
BW = 133.0                 # 기준부재(그룹#28) 비례 160/120 -> H100 환산 133.3 -> 133
YMID = 8142.55
y0 = 7562.2; y1 = y0 + BW  # 7695.2
mir = lambda{|y| 2*YMID - y}
secL = [[y0,0],[y1,0],[y1,H],[y1-T,H],[y1-T,T],[y0+T,T],[y0+T,H],[y0,H]]
secR = secL.map{|y,z| [mir.call(y), z]}.reverse
puts "secL y=#{secL.map{|a,_| a}.minmax.inspect} secR y=#{secR.map{|a,_| a}.minmax.inspect} len=#{(U1-U0).round(2)}"
trL = Geom::Transformation.axes(Geom::Point3d.new(xL0*MM,0,zL0*MM),
        Geom::Vector3d.new(1,0,-mL).normalize, Geom::Vector3d.new(0,1,0),
        Geom::Vector3d.new(mL,0,1).normalize)
begin
  m.start_operation("사이드채널 재작성", true)
  old = m.entities.grep(Sketchup::Group).find{|g| g.name=="사이드채널_H100_20260919"}
  if old; old.name = "사이드채널_구안_C100x50_hidden"; old.hidden = true; puts "  구안 rename+hidden"; end
  root = m.entities.add_group; root.name = "사이드채널_H100_20260919"
  [["채널_좌_H100xB133xt12", secL],["채널_우_H100xB133xt12", secR]].each do |nm, sec|
    g = root.entities.add_group; g.name = nm
    f = g.entities.add_face(sec.map{|y,z| Geom::Point3d.new(U0*MM, y*MM, z*MM)})
    d = f.normal.x > 0 ? (U1-U0) : -(U1-U0)
    f.pushpull(d*MM)
    puts "  #{nm} solid=#{g.manifold?} vol=#{(g.volume*16387.064/1000).round(1)}cm3"
  end
  root.transformation = trL
  m.commit_operation
  ys=[]
  root.entities.grep(Sketchup::Group).each{|g| g.entities.grep(Sketchup::Face).each{|f| f.vertices.each{|v| ys << (v.position.transform(g.transformation*root.transformation).y*25.4).round(2)}}}
  ys.uniq!
  bad = ys.reject{|y| ys.any?{|o| ((2*YMID-y)-o).abs < 0.05}}
  puts "SYMMETRY uniqueY=#{ys.sort.inspect} mismatch=#{bad.length}"
  b=root.bounds
  puts "BBOX mm min=(#{(b.min.x*25.4).round(1)},#{(b.min.y*25.4).round(1)},#{(b.min.z*25.4).round(1)}) max=(#{(b.max.x*25.4).round(1)},#{(b.max.y*25.4).round(1)},#{(b.max.z*25.4).round(1)})"
  m.selection.clear; m.selection.add(root); m.active_view.zoom(root)
  puts "SEL=#{m.selection.length}"
rescue Exception => ex
  m.commit_operation rescue nil
  puts "ERR #{ex.class}: #{ex.message}"
end
"CH2"
