require_relative '../helpers/github'
require_relative '../helpers/git'

module Fastlane
  module Actions
    class SubtreesConfigAction < Action
      def self.run(params)
        config_file = params[:config]
        config = YAML.load_file(File.join(Git.root, config_file))
        unless config.is_a?(Hash)
          UI.user_error!("Invalid subtrees configuration file: #{config_file}")
        end
        config.each do |subtree, subtree_config|
          unless subtree_config.has_key?("repo")
            UI.user_error!("Invalid configuration for subtree '#{subtree}': missing :repo key.")
          end
          unless subtree_config.has_key?("branch")
            UI.user_error!("Invalid configuration for subtree '#{subtree}': missing :branch key.")
          end
        end
        config
      end

      def self.description
        "Reads the subtrees configuration file and returns a hash of subtrees and their configuration"
      end

      def self.authors
        ["Suno"]
      end

      def self.return_value
        "Returns a hash of subtrees and their configuration"
      end

      def self.available_options
        [
          FastlaneCore::ConfigItem.new(
            key: :config,
            description: "Subtrees configuration file (defaults to .gitsubtrees)",
            type: String,
            default_value: ".gitsubtrees",
            verify_block: proc do |value|
              UI.user_error!(':config option must point to an existing file') unless File.exist?(File.join(Git.root, value))
            end
          ),
        ]
      end

      def self.is_supported?(platform)
        true
      end
    end
  end
end
