# -*- coding: utf-8 -*-
# 1단계: 현재 선택(Selection) 전체 읽기
MM = 25.4
def f(v); (v*1.0/MM).round(1); end
m = Sketchup.active_model
sel = m.selection
puts "MODEL: #{m.title}"
puts "SEL_COUNT: #{sel.count}"
if sel.count == 0
  puts "STOP: 선택이 0개입니다. 아무것도 하지 않음."
else
  sel.each_with_index do |e, i|
    puts "--- [#{i}] #{e.class.name} eid=#{e.entityID}"
    nm = ""
    begin
      nm = e.name if e.respond_to?(:name)
    rescue; end
    puts "    name=#{nm.inspect}"
    if e.respond_to?(:definition)
      begin
        puts "    defname=#{e.definition.name.inspect} inst_count=#{e.definition.count_instances}"
      rescue; end
    end
    begin
      bb = e.bounds
      puts "    BBOX mm: X #{f(bb.min.x)} ~ #{f(bb.max.x)}  (W #{f(bb.width)})"
      puts "    BBOX mm: Y #{f(bb.min.y)} ~ #{f(bb.max.y)}  (D #{f(bb.depth)})"
      puts "    BBOX mm: Z #{f(bb.min.z)} ~ #{f(bb.max.z)}  (H #{f(bb.height)})"
    rescue => ex; puts "    bbox err #{ex}"; end
    begin
      puts "    layer=#{e.layer.name.inspect}" if e.respond_to?(:layer)
      puts "    material=#{(e.material ? e.material.name : 'nil')}" if e.respond_to?(:material)
      puts "    hidden=#{e.hidden?}" if e.respond_to?(:hidden?)
      if e.respond_to?(:transformation)
        t = e.transformation
        o = t.origin
        puts "    origin mm: #{f(o.x)}, #{f(o.y)}, #{f(o.z)}"
      end
    rescue; end
    # 하위 구성
    if e.respond_to?(:entities)
      ents = e.entities
      cnt = Hash.new(0)
      ents.each { |c| cnt[c.class.name] += 1 }
      puts "    CHILD: #{cnt.inspect} (total #{ents.count})"
      subs = ents.grep(Sketchup::Group) + ents.grep(Sketchup::ComponentInstance)
      subs.each_with_index do |s, j|
        next if j > 40
        sb = s.bounds
        snm = (s.respond_to?(:name) ? s.name : "")
        sdn = ""
        begin; sdn = s.definition.name; rescue; end
        puts "      sub[#{j}] #{s.class.name} name=#{snm.inspect} def=#{sdn.inspect} " \
             "X #{f(sb.min.x)}~#{f(sb.max.x)} Y #{f(sb.min.y)}~#{f(sb.max.y)} Z #{f(sb.min.z)}~#{f(sb.max.z)} " \
             "(#{f(sb.width)} x #{f(sb.depth)} x #{f(sb.height)})"
      end
      puts "      ...sub total #{subs.size}" if subs.size > 41
      # 원(구멍) 검출
      circles = ents.grep(Sketchup::Edge).map { |ed| ed.curve }.compact.uniq
      arcs = circles.select { |c| c.is_a?(Sketchup::ArcCurve) }
      if arcs.size > 0
        rad = Hash.new(0)
        arcs.each { |a| rad[f(a.radius*2).to_s] += 1 rescue nil }
        puts "    HOLES(top-level) dia_mm=>count: #{rad.inspect}"
      end
      # 면 두께 추정: 가장 얇은 방향
      puts "    FACES: #{ents.grep(Sketchup::Face).size}"
    end
  end
end
puts "IME_CHECK: (콘솔 미개방)"
"DONE_SEL_READ"
