# encoding: UTF-8
# rdsel — 선택 읽기 + 최근 생성 후보 (읽기 전용)
MM = 25.4
def r1(v); (v * 25.4).round(1); end
m = Sketchup.active_model
out = []
sel = m.selection.to_a
out << "SEL COUNT=#{sel.length}"
sel.each_with_index do |e, i|
  out << "[#{i}] #{e.class} name=#{(e.respond_to?(:name) ? e.name : '').inspect} eid=#{e.entityID}"
  if e.respond_to?(:bounds)
    b = e.bounds
    out << "    bbox (#{r1(b.min.x)},#{r1(b.min.y)},#{r1(b.min.z)})..(#{r1(b.max.x)},#{r1(b.max.y)},#{r1(b.max.z)}) 크기 #{r1(b.width)}x#{r1(b.height)}x#{r1(b.depth)}"
  end
  if e.is_a?(Sketchup::Face)
    out << "    면적 #{(e.area*645.16).round(0)}mm2 법선 (#{e.normal.x.round(4)},#{e.normal.y.round(4)},#{e.normal.z.round(4)}) 정점 #{e.vertices.length} parent=#{e.parent.class}"
  elsif e.respond_to?(:entities) || e.is_a?(Sketchup::ComponentInstance)
    ents = e.is_a?(Sketchup::ComponentInstance) ? e.definition.entities : e.entities
    out << "    ents=#{ents.length} faces=#{ents.grep(Sketchup::Face).length} solid=#{(e.manifold? rescue 'n/a')} parent=#{(e.parent.respond_to?(:name) ? e.parent.name : e.parent.class)}"
  end
end
out << "== 최상위 엔티티 최신 20개 (entityID 큰 순) =="
m.entities.to_a.select { |e| e.is_a?(Sketchup::Group) || e.is_a?(Sketchup::ComponentInstance) || e.is_a?(Sketchup::Face) }
 .sort_by { |e| -e.entityID }[0, 20].each do |e|
  b = e.bounds
  nm = e.respond_to?(:name) ? e.name : ""
  nm = e.definition.name if nm.to_s.empty? && e.respond_to?(:definition)
  out << "  eid=#{e.entityID} #{e.class} #{nm.inspect} bbox (#{r1(b.min.x)},#{r1(b.min.y)},#{r1(b.min.z)})..(#{r1(b.max.x)},#{r1(b.max.y)},#{r1(b.max.z)})"
end
g2 = m.entities.grep(Sketchup::Group).find { |g| g.definition.name == "그룹#2" }
if g2
  out << "== 그룹#2 내부 최신 =="
  g2.entities.to_a.sort_by { |e| -e.entityID }[0, 10].each do |e|
    next unless e.is_a?(Sketchup::Group) || e.is_a?(Sketchup::Face) || e.is_a?(Sketchup::ComponentInstance)
    b = e.bounds
    nm = e.respond_to?(:name) ? e.name : ""
    out << "  eid=#{e.entityID} #{e.class} #{nm.inspect} bbox (#{r1(b.min.x)},#{r1(b.min.y)},#{r1(b.min.z)})..(#{r1(b.max.x)},#{r1(b.max.y)},#{r1(b.max.z)})"
  end
end
puts out.join("\n")
"RDSEL"
