# frozen_string_literal: true

require 'nokogiri'

class Hash
  class << self
    def from_xml(data)
      result = Nokogiri::XML(data)
      return { result.root.name => xml_node_to_hash(result.root) }
    end

    private def xml_node_to_hash(node)
      return node.content.to_s unless node.element?
      result_hash = {}
      attributes = node.attributes.keys.map { |k| [node.attributes[k].name, node.attributes[k].value] }.to_h
      node.children.each do |child|
        result = xml_node_to_hash(child)
        return result if child.name == 'text' && !(child.next_sibling || child.previous_sibling) && attributes.empty?
        if result_hash.key?(child.name)
          result_hash[child.name] = [result_hash[child.name]] unless result_hash[child.name].is_a?(Object::Array)
          result_hash[child.name] << result
        else
          result_hash[child.name] = result
        end
      end
      result_hash = attributes.merge(result_hash) unless attributes.empty?
      return result_hash
    end
  end
end
