#!/usr/bin/env ruby
# frozen_string_literal: true

require 'nokogiri'
require 'set'

# 1) Process all files passed in from the command line
svgpath = ARGV[0]
files = ARGV[1..]

# 2) Extract used Feather icons
used_icons = Set.new

files.each do |file|
  # Parse each HTML file
  doc = File.open(file, "r:UTF-8") { |f| Nokogiri::HTML(f) }

  # Look for <use xlink:href="/feather-sprite.svg#iconName">
  doc.css("use").each do |use_tag|
    href = use_tag["xlink:href"] || use_tag["href"]
    if href && href.start_with?("/feather-sprite.svg#")
      icon_name = href.split("#").last
      used_icons << icon_name
    end
  end
end

puts "Found #{used_icons.size} unique icons: #{used_icons.to_a.join(', ')}"

# 3) Load the full feather-sprite.svg as XML
sprite_doc = File.open(svgpath, "r:UTF-8") { |f| Nokogiri::XML(f) }

# 4) Create a new SVG with only the required symbols
new_svg = Nokogiri::XML::Document.new
svg_tag = Nokogiri::XML::Node.new("svg", new_svg)
svg_tag["xmlns"] = "http://www.w3.org/2000/svg"
new_svg.add_child(svg_tag)

sprite_doc.css("symbol").each do |symbol_node|
  if used_icons.include?(symbol_node["id"])
    # Duplicate the symbol node (so it can be inserted in the new document)
    svg_tag.add_child(symbol_node.dup)
  end
end

# 5) Save the subset sprite
File.open(svgpath, "w:UTF-8") do |f|
  f.write(new_svg.to_xml)
end
