# encoding: UTF-8
begin
  puts "###DZW-REVERT-H80-20260920"
  m = Sketchup.active_model
  bk = 'E:/도진팩토리/3D스캔및티칭시스템/_자동화/autosave/BACKUP_before_revertH80.skp'
  m.save_copy(bk)
  puts "BACKUP=#{bk}"
  del = ['RJ102-0604_LH_H80_20260920', 'RJ102-0602_RH_H80_20260920']
  unh = ['RJ102-0604_LH_20260918', 'RJ102-0602_RH_20260918']
  found = {}
  m.active_entities.each do |e|
    next unless e.is_a?(Sketchup::Group) || e.is_a?(Sketchup::ComponentInstance)
    nm = (e.respond_to?(:name) ? e.name.to_s : '')
    found[nm] = e unless nm.empty?
  end
  m.start_operation('H80 롤백', true)
  del.each do |nm|
    e = found[nm]
    if e && e.valid?
      e.erase!
      puts "삭제 '#{nm}'"
    else
      puts "미발견 '#{nm}'"
    end
  end
  unh.each do |nm|
    e = found[nm]
    if e && e.valid?
      e.hidden = false
      puts "복구 '#{nm}' hidden=#{e.hidden?}"
    else
      puts "미발견 '#{nm}'"
    end
  end
  m.commit_operation

  puts "-- 월드 좌표 감사 (model.active_entities = 모델 루트, bounds 는 이미 월드) --"
  ['그룹#1_14T절곡', 'RJ102-0604_LH_20260918', 'RJ102-0602_RH_20260918', '하부프레임커버'].each do |nm|
    e = found[nm]
    next puts "  미발견 '#{nm}'" unless e && e.valid?
    tr = e.transformation
    b = e.bounds
    puts "  '#{nm}' tr.origin(world)=#{tr.origin.to_a.map { |v| v.to_mm.round(1) }.inspect} scale=[#{tr.xscale.round(4)},#{tr.yscale.round(4)},#{tr.zscale.round(4)}]"
    puts "     bounds(world) min=#{b.min.to_a.map { |v| v.to_mm.round(1) }.inspect} max=#{b.max.to_a.map { |v| v.to_mm.round(1) }.inspect}"
    if nm.start_with?('RJ102-06')
      pts = []
      e.entities.grep(Sketchup::Edge).each { |ed| ed.vertices.each { |v| pts << v.position.transform(tr) } }
      xs = pts.map { |p| p.x.to_mm }
      ux = xs.uniq.sort
      gi = 0
      gv = -1.0
      (0...(ux.length - 1)).each do |i|
        dd = ux[i + 1] - ux[i]
        if dd > gv
          gv = dd
          gi = i
        end
      end
      lx = pts.map { |p| p.x.to_mm }
      puts "     로컬X범위=#{e.entities.grep(Sketchup::Edge).flat_map { |ed| ed.vertices.map { |v| v.position.x.to_mm } }.minmax.map { |v| v.round(1) }.inspect} / 월드X범위=#{lx.minmax.map { |v| v.round(1) }.inspect}"
      puts "     절곡선(월드X, 최대간격 앞쪽 끝)=#{ux[gi].round(1)}  앞끝(월드X)=#{ux[0].round(1)}"
    end
  end
  ok = m.save
  puts "SAVE=#{ok.inspect} modified?=#{m.modified?.inspect}"
  puts "DONE"
rescue Exception => e
  puts "EXC #{e.class}: #{e.message}"
  puts e.backtrace.first(5).join(" | ")
end
nil
