# encoding: UTF-8
begin
  puts "###DZW-OILCOVER-FIX-20260920"
  m = Sketchup.active_model
  bk = 'E:/도진팩토리/3D스캔및티칭시스템/_자동화/autosave/BACKUP_before_oilcover_fix.skp'
  m.save_copy(bk)
  puts "BACKUP=#{bk}"
  names = ['오일탱크커버_A_420_20260920', '오일탱크커버_B_420_20260920']
  m.start_operation('오일탱크커버 재생성', true)
  m.entities.to_a.each do |e|
    next unless e.is_a?(Sketchup::Group) || e.is_a?(Sketchup::ComponentInstance)
    nm = (e.respond_to?(:name) ? e.name.to_s : '')
    if names.include?(nm) && e.valid?
      e.erase!
      puts "이전 빈 그룹 삭제 '#{nm}'"
    end
  end
  x0 = 4478.4
  y0 = 7562.2
  y1 = 8722.9
  th = 12.0
  seat = 93.81
  made = []
  2.times do |k|
    xa = x0 + 420.0 * k
    xb = xa + 420.0
    nm = names[k]
    g = m.entities.add_group
    z = seat
    g.entities.add_face([
      Geom::Point3d.new(xa.mm, y0.mm, z.mm),
      Geom::Point3d.new(xb.mm, y0.mm, z.mm),
      Geom::Point3d.new(xb.mm, y1.mm, z.mm),
      Geom::Point3d.new(xa.mm, y1.mm, z.mm)
    ])
    [y0 + 30.0, y1 - 30.0].each do |yy|
      4.times do |i|
        cx = xa + 40.0 + 113.3 * i
        g.entities.add_circle(Geom::Point3d.new(cx.mm, yy.mm, z.mm), Geom::Vector3d.new(0, 0, 1), 9.0.mm, 16)
      end
    end
    fs = g.entities.grep(Sketchup::Face)
    areas = fs.map { |f| (f.area * 645.16).round(0) }
    puts "  #{nm}: 면 #{fs.length}개, 면적(mm2) 최대 #{areas.max} / 최소 #{areas.min}"
    small = fs.select { |f| (f.area * 645.16) < 1000.0 }
    g.entities.erase_entities(small) unless small.empty?
    big = g.entities.grep(Sketchup::Face).max_by { |f| f.area }
    if big.nil?
      puts "  STOP: #{nm} 본체 면 없음"
      next
    end
    big.pushpull(th.mm)
    g.name = nm
    holes = 0
    g.entities.grep(Sketchup::Face).each { |f| f.loops.each { |lp| holes += 1 if !lp.outer? && lp.vertices.length >= 8 } }
    made << [nm, g, holes, small.length]
  end
  m.commit_operation
  ok_all = true
  made.each do |nm, g, holes, ns|
    b = g.bounds
    hgt = (b.max.z.to_mm - b.min.z.to_mm).round(2)
    ok_all = false if hgt < 11.0 || g.entities.grep(Sketchup::Face).length < 6
    puts "== #{nm} bbox 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} 두께=#{hgt} 면수=#{g.entities.grep(Sketchup::Face).length} 홀루프=#{holes} (원형면 #{ns}개 제거)"
  end
  puts "검증: #{ok_all && made.length == 2 ? '정상(2장 입체 생성)' : '이상 있음'}"
  vw = m.active_view
  cam0 = vw.camera
  begin
    c = Geom::Point3d.new((x0 + 420.0).mm, ((y0 + y1) / 2.0).mm, seat.mm)
    [['bottom', Geom::Point3d.new(c.x.to_f, c.y.to_f, c.z - 2200.mm), Geom::Vector3d.new(1, 0, 0)],
     ['iso', Geom::Point3d.new(c.x - 2200.mm, c.y - 2600.mm, c.z - 1400.mm), Geom::Vector3d.new(0, 0, 1)]].each do |tag, eye, upv|
      vw.camera = Sketchup::Camera.new(eye, c, upv)
      f = "E:/도진팩토리/3D스캔및티칭시스템/_자동화/inbox/_oilcov3_#{tag}.png"
      vw.write_image(f, 1600, 1000, true)
      puts "캡처 #{tag}=#{f} 존재=#{File.exist?(f)}"
    end
  rescue Exception => e3
    puts "캡처 실패 #{e3.message}"
  ensure
    vw.camera = cam0
  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(6).join(" | ")
end
nil
