# encoding: UTF-8
begin
  puts "###DZW-COVER-FIT-20260920"
  m = Sketchup.active_model
  bk = 'E:/도진팩토리/3D스캔및티칭시스템/_자동화/autosave/BACKUP_before_coverfit.skp'
  m.save_copy(bk)
  puts "BACKUP=#{bk}"
  cov = nil
  lh = nil
  rh = nil
  others = []
  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 : '')
    case nm
    when '하부프레임커버' then cov = e
    when 'RJ102-0604_LH_20260918' then lh = e
    when 'RJ102-0602_RH_20260918' then rh = e
    end
    nmx = nm.empty? && e.is_a?(Sketchup::ComponentInstance) ? e.definition.name.to_s : nm
    others << [e, nmx] unless nm == '하부프레임커버'
  end
  if cov.nil? || lh.nil? || rh.nil?
    puts "STOP: 대상 미발견 cover=#{!cov.nil?} lh=#{!lh.nil?} rh=#{!rh.nil?}"
  else
    cb = cov.bounds
    lb = lh.bounds
    rb = rh.bounds
    cy0 = cb.min.y.to_mm
    cy1 = cb.max.y.to_mm
    lin = lb.max.y.to_mm   # LH 사이드 안쪽 면(+Y 쪽)
    rin = rb.min.y.to_mm   # RH 사이드 안쪽 면(-Y 쪽)
    gapw = rin - lin
    covw = cy1 - cy0
    puts "[월드] 커버 Y=[#{cy0.round(1)},#{cy1.round(1)}] 폭=#{covw.round(1)}"
    puts "[월드] LH 사이드 Y=[#{lb.min.y.to_mm.round(1)},#{lb.max.y.to_mm.round(1)}] 안쪽면=#{lin.round(1)}"
    puts "[월드] RH 사이드 Y=[#{rb.min.y.to_mm.round(1)},#{rb.max.y.to_mm.round(1)}] 안쪽면=#{rin.round(1)}"
    puts "[월드] 사이드 안쪽 간격=#{gapw.round(1)} / 커버 폭=#{covw.round(1)} / 차=#{(gapw - covw).round(1)}"
    if covw > gapw + 0.5
      puts "STOP: 커버 폭이 사이드 안쪽 간격보다 #{(covw - gapw).round(1)}mm 큼 -> 양쪽 밀착 불가. 이동하지 않음(형상 변경 금지)."
      puts "  참고: LH 기준 밀착 시 이동 dY=#{(lin - cy0).round(1)}, 이때 RH측 겹침=#{(covw - gapw).round(1)}mm"
      puts "  참고: RH 기준 밀착 시 이동 dY=#{(rin - cy1).round(1)}, 이때 LH측 겹침=#{(covw - gapw).round(1)}mm"
    else
      dy = lin - cy0
      m.start_operation('하부프레임커버 사이드 밀착', true)
      cov.transform!(Geom::Transformation.new(Geom::Vector3d.new(0, dy.mm, 0)))
      m.commit_operation
      nb = cov.bounds
      ny0 = nb.min.y.to_mm
      ny1 = nb.max.y.to_mm
      puts "이동 dY=#{dy.round(2)}mm -> 커버 Y=[#{ny0.round(1)},#{ny1.round(1)}]"
      puts "LH측 틈=#{(ny0 - lin).round(2)}mm / RH측 틈=#{(rin - ny1).round(2)}mm"
      ov = []
      others.each do |e, onm|
        ob = e.bounds
        ox = [ob.max.x.to_mm, nb.max.x.to_mm].min - [ob.min.x.to_mm, nb.min.x.to_mm].max
        oy = [ob.max.y.to_mm, nb.max.y.to_mm].min - [ob.min.y.to_mm, nb.min.y.to_mm].max
        oz = [ob.max.z.to_mm, nb.max.z.to_mm].min - [ob.min.z.to_mm, nb.min.z.to_mm].max
        next unless ox > 0.5 && oy > 0.5 && oz > 0.5
        ov << "   BBOX겹침 '#{onm}' #{ox.round(1)}x#{oy.round(1)}x#{oz.round(1)}"
      end
      puts "bbox 겹침 #{ov.length}건"
      ov.first(12).each { |s| puts s }
      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(5).join(" | ")
end
nil
