# encoding: UTF-8
begin
  puts "###DZW-STEP1B-SLOPE-20260920"
  m = Sketchup.active_model
  bk = 'E:/도진팩토리/3D스캔및티칭시스템/_자동화/autosave/BACKUP_before_step1b.skp'
  m.save_copy(bk)
  puts "BACKUP=#{bk}"
  tgt = 6.4452
  cov = nil
  m.active_entities.each do |e|
    next unless e.is_a?(Sketchup::Group) || e.is_a?(Sketchup::ComponentInstance)
    cov = e if (e.respond_to?(:name) ? e.name.to_s : '') == '하부프레임커버'
  end
  k = nil
  if cov
    (cov.entities.grep(Sketchup::Group) + cov.entities.grep(Sketchup::ComponentInstance)).each do |q|
      k = q if (q.respond_to?(:name) ? q.name.to_s : '') == '조립부원판_20260919'
    end
  end
  if k.nil?
    puts "STOP: 조립부원판 미발견"
  else
    ct = cov.transformation
    wt = ct * k.transformation
    pts = []
    k.entities.grep(Sketchup::Edge).each { |ed| ed.vertices.each { |v| pts << v.position.transform(wt) } }
    xs = pts.map { |p| p.x.to_mm }
    zs = pts.map { |p| p.z.to_mm }
    xmin = xs.min
    xmax = xs.max
    zf = pts.select { |p| p.x.to_mm <= xmin + 1.0 }.map { |p| p.z.to_mm }.min   # 앞(저X) 하면
    zr = pts.select { |p| p.x.to_mm >= xmax - 1.0 }.map { |p| p.z.to_mm }.min   # 뒤(고X) 하면
    run = xmax - xmin
    cur = Math.atan((zf - zr) / run) * 180.0 / Math::PI
    da = tgt - cur
    rise = run * Math.tan(tgt * Math::PI / 180.0)
    puts "검산: 앞X=#{xmin.round(1)}(하면Z #{zf.round(2)}) 뒤X=#{xmax.round(1)}(하면Z #{zr.round(2)}) 런=#{run.round(1)}"
    puts "검산: 현재 기울기=#{cur.round(4)}deg -> 목표 #{tgt}deg, 회전량 #{da.round(4)}deg (피벗=뒤쪽 모서리 X#{xmax.round(1)}/Z#{zr.round(2)}, 앞끝 상승 예상 #{(rise - (zf - zr)).round(1)}mm)"
    if da.abs > 20.0 || (rise - (zf - zr)).abs > 300.0
      puts "STOP: 검산 범위 초과 -> 변경 없음"
    else
      piv = Geom::Point3d.new(xmax.mm, 0, zr.mm)
      rw = Geom::Transformation.rotation(piv, Geom::Vector3d.new(0, 1, 0), da * Math::PI / 180.0)
      tl = ct.inverse * rw * ct
      m.start_operation('하판 경사 6.4452 복원', true)
      k.transform!(tl)
      m.commit_operation
      wt2 = ct * k.transformation
      p2 = []
      k.entities.grep(Sketchup::Edge).each { |ed| ed.vertices.each { |v| p2 << v.position.transform(wt2) } }
      x2 = p2.map { |p| p.x.to_mm }
      z2 = p2.map { |p| p.z.to_mm }
      zf2 = p2.select { |p| p.x.to_mm <= x2.min + 1.0 }.map { |p| p.z.to_mm }.min
      zr2 = p2.select { |p| p.x.to_mm >= x2.max - 1.0 }.map { |p| p.z.to_mm }.min
      ang2 = Math.atan((zf2 - zr2) / (x2.max - x2.min)) * 180.0 / Math::PI
      puts "== 결과: 기울기 #{cur.round(4)} -> #{ang2.round(4)}deg (목표 #{tgt})"
      puts "   월드 X=[#{x2.min.round(1)},#{x2.max.round(1)}] Z=[#{z2.min.round(1)},#{z2.max.round(1)}] 앞하면Z #{zf.round(1)}->#{zf2.round(1)} 뒤하면Z #{zr.round(1)}->#{zr2.round(1)}"
      puts "   scale=[#{k.transformation.xscale.round(5)},#{k.transformation.yscale.round(5)},#{k.transformation.zscale.round(5)}]"
      ok = m.save
      puts "SAVE=#{ok.inspect} modified?=#{m.modified?.inspect}"
      puts "DONE"
    end
  end
rescue Exception => e
  puts "EXC #{e.class}: #{e.message}"
  puts e.backtrace.first(6).join(" | ")
end
nil
