# typed: strict
# frozen_string_literal: true

require "abstract_command"
require "env_config"
require "cask/config"
require "cli/args"
require "cli/error"
require "commands"
require "extend/ENV/sensitive"
require "optparse"
require "utils/tty"
require "utils/formatter"
require "utils/output"

module Homebrew
  module CLI
    class Parser
      include Utils::Output::Mixin

      ArgType = T.type_alias { T.nilable(T.any(Symbol, T::Array[String], T::Array[Symbol])) }
      HIDDEN_DESC_PLACEHOLDER = "@@HIDDEN@@"
      SYMBOL_TO_USAGE_MAPPING = T.let({
        service:       "<service>",
        text_or_regex: "<text>|`/`<regex>`/`",
        url:           "<URL>",
      }.freeze, T::Hash[Symbol, String])
      private_constant :ArgType, :HIDDEN_DESC_PLACEHOLDER, :SYMBOL_TO_USAGE_MAPPING

      class Subcommand < T::Struct
        const :name, String
        const :aliases, T::Array[String], default: []
        const :alias_options, T::Hash[String, String], default: {}
        prop :description, T.nilable(String), default: nil
        prop :usage_banner, T.nilable(String), default: nil
        const :default, T::Boolean, default: false
        prop :named_args_type, ArgType, default: nil
        prop :max_named_args, T.nilable(Integer), default: nil
        prop :min_named_args, T.nilable(Integer), default: nil
        prop :named_args_without_api, T::Boolean, default: false
        const :hidden, T::Boolean, default: false
        const :replacement, T.nilable(T.any(String, Symbol)), default: nil
        const :odeprecated, T::Boolean, default: false
        const :odisabled, T::Boolean, default: false
      end

      sig { returns(Args) }
      attr_reader :args

      sig { returns(Args::OptionsType) }
      attr_reader :processed_options

      sig { returns(T::Boolean) }
      attr_reader :hide_from_man_page

      sig { returns(T::Array[Subcommand]) }
      attr_reader :subcommands

      sig { returns(T.nilable(Integer)) }
      attr_reader :min_named_args

      sig { params(cmd_path: Pathname).returns(T.nilable(CLI::Parser)) }
      def self.from_cmd_path(cmd_path)
        cmd_args_method_name = Commands.args_method_name(cmd_path)
        cmd_name = cmd_args_method_name.to_s.delete_suffix("_args").tr("_", "-")

        begin
          if ENV.clear_sensitive_environment! { Homebrew.require?(cmd_path) }
            cmd = Homebrew::AbstractCommand.command(cmd_name)
            if cmd
              cmd.parser
            else
              # FIXME: remove once commands are all subclasses of `AbstractCommand`:
              Homebrew.send(cmd_args_method_name)
            end
          end
        rescue NoMethodError => e
          raise if e.name.to_sym != cmd_args_method_name

          nil
        end
      end

      sig { returns(T::Array[[Symbol, String, { description: String }]]) }
      def self.global_cask_options
        [
          [:flag, "--appdir=", {
            description: "Target location for Applications " \
                         "(default: `#{Cask::Config::DEFAULT_DIRS[:appdir]}`).",
          }],
          [:flag, "--appimagedir=", {
            description: "Target location for AppImages " \
                         "(default: `#{Cask::Config::DEFAULT_DIRS[:appimagedir]}`).",
          }],
          [:flag, "--keyboard-layoutdir=", {
            description: "Target location for Keyboard Layouts " \
                         "(default: `#{Cask::Config::DEFAULT_DIRS[:keyboard_layoutdir]}`).",
          }],
          [:flag, "--colorpickerdir=", {
            description: "Target location for Color Pickers " \
                         "(default: `#{Cask::Config::DEFAULT_DIRS[:colorpickerdir]}`).",
          }],
          [:flag, "--prefpanedir=", {
            description: "Target location for Preference Panes " \
                         "(default: `#{Cask::Config::DEFAULT_DIRS[:prefpanedir]}`).",
          }],
          [:flag, "--qlplugindir=", {
            description: "Target location for Quick Look Plugins " \
                         "(default: `#{Cask::Config::DEFAULT_DIRS[:qlplugindir]}`).",
          }],
          [:flag, "--mdimporterdir=", {
            description: "Target location for Spotlight Plugins " \
                         "(default: `#{Cask::Config::DEFAULT_DIRS[:mdimporterdir]}`).",
          }],
          [:flag, "--dictionarydir=", {
            description: "Target location for Dictionaries " \
                         "(default: `#{Cask::Config::DEFAULT_DIRS[:dictionarydir]}`).",
          }],
          [:flag, "--fontdir=", {
            description: "Target location for Fonts " \
                         "(default: `#{Cask::Config::DEFAULT_DIRS[:fontdir]}`).",
          }],
          [:flag, "--servicedir=", {
            description: "Target location for Services " \
                         "(default: `#{Cask::Config::DEFAULT_DIRS[:servicedir]}`).",
          }],
          [:flag, "--input-methoddir=", {
            description: "Target location for Input Methods " \
                         "(default: `#{Cask::Config::DEFAULT_DIRS[:input_methoddir]}`).",
          }],
          [:flag, "--internet-plugindir=", {
            description: "Target location for Internet Plugins " \
                         "(default: `#{Cask::Config::DEFAULT_DIRS[:internet_plugindir]}`).",
          }],
          [:flag, "--audio-unit-plugindir=", {
            description: "Target location for Audio Unit Plugins " \
                         "(default: `#{Cask::Config::DEFAULT_DIRS[:audio_unit_plugindir]}`).",
          }],
          [:flag, "--vst-plugindir=", {
            description: "Target location for VST Plugins " \
                         "(default: `#{Cask::Config::DEFAULT_DIRS[:vst_plugindir]}`).",
          }],
          [:flag, "--vst3-plugindir=", {
            description: "Target location for VST3 Plugins " \
                         "(default: `#{Cask::Config::DEFAULT_DIRS[:vst3_plugindir]}`).",
          }],
          [:flag, "--screen-saverdir=", {
            description: "Target location for Screen Savers " \
                         "(default: `#{Cask::Config::DEFAULT_DIRS[:screen_saverdir]}`).",
          }],
          [:comma_array, "--language", {
            description: "Comma-separated list of language codes to prefer for cask installation. " \
                         "The first matching language is used, otherwise it reverts to the cask's " \
                         "default language. The default value is the language of your system.",
          }],
        ]
      end

      sig { returns(T::Array[[String, String, String]]) }
      def self.global_options
        [
          ["-d", "--debug",   "Display any debugging information."],
          ["-q", "--quiet",   "Make some output more quiet."],
          ["-v", "--verbose", "Make some output more verbose."],
          ["-h", "--help",    "Show this message."],
        ]
      end

      sig { params(option: String).returns(String) }
      def self.option_to_name(option)
        option.sub(/\A--?(\[no-\])?/, "").tr("-", "_").delete("=")
      end

      sig {
        params(cmd: T.class_of(Homebrew::AbstractCommand), block: T.nilable(T.proc.bind(Parser).void)).void
      }
      def initialize(cmd, &block)
        @parser = T.let(OptionParser.new, OptionParser)
        @parser.summary_indent = "  "
        # Disable default handling of `--version` switch.
        @parser.base.long.delete("version")
        # Disable default handling of `--help` switch.
        @parser.base.long.delete("help")

        @args = T.let((cmd.args_class || Args).new, Args)

        @command_name = T.let(cmd.command_name, String)
        @is_dev_cmd = T.let(cmd.dev_cmd?, T::Boolean)

        @constraints = T.let([], T::Array[[String, String, T.nilable(T::Array[String])]])
        @conflicts = T.let([], T::Array[T::Array[String]])
        @switch_sources = T.let({}, T::Hash[String, Symbol])
        @option_sources = T.let({}, T::Hash[String, Symbol])
        @option_subcommands = T.let({}, T::Hash[String, T::Array[String]])
        @option_types = T.let({}, T::Hash[String, Symbol])
        @processed_options = T.let([], Args::OptionsType)
        @processed_option_summaries = T.let([], T::Array[[T.untyped, T::Boolean]])
        @processed_options_by_subcommand = T.let({}, T::Hash[T.nilable(String), Args::OptionsType])
        @processed_option_summaries_by_subcommand =
          T.let({}, T::Hash[T.nilable(String), T::Array[[T.untyped, T::Boolean]]])
        @non_global_processed_options = T.let([], T::Array[[String, ArgType]])
        @named_args_type = T.let(nil, T.nilable(ArgType))
        @max_named_args = T.let(nil, T.nilable(Integer))
        @min_named_args = T.let(nil, T.nilable(Integer))
        @named_args_without_api = T.let(false, T::Boolean)
        @description = T.let(nil, T.nilable(String))
        @usage_banner = T.let(nil, T.nilable(String))
        @hide_from_man_page = T.let(false, T::Boolean)
        @formula_options = T.let(false, T::Boolean)
        @cask_options = T.let(false, T::Boolean)
        @subcommands = T.let([], T::Array[Subcommand])
        @current_subcommands = T.let(nil, T.nilable(T::Array[String]))

        self.class.global_options.each do |short, long, desc|
          switch short, long, description: desc, env: option_to_name(long), method: :on_tail
        end

        instance_eval(&block) if block

        generate_banner
      end

      sig {
        params(names: String, description: T.nilable(String), env: T.untyped,
               depends_on: T.nilable(String), method: Symbol,
               hidden: T::Boolean, replacement: T.nilable(T.any(String, FalseClass)),
               odeprecated: T::Boolean, odisabled: T::Boolean,
               subcommands: T.nilable(T.any(String, T::Array[String]))).void
      }
      def switch(*names, description: nil, env: nil,
                 depends_on: nil, method: :on,
                 hidden: false, replacement: nil,
                 odeprecated: false, odisabled: false,
                 subcommands: nil)
        global_switch = names.first.is_a?(Symbol)
        return if global_switch

        hidden = true if odisabled || odeprecated

        description = option_description(description, *names, hidden:)
        env, counterpart = env
        if env
          env_hidden = Homebrew::EnvConfig.hidden?(Homebrew::EnvConfig::ENVS.fetch(:"HOMEBREW_#{env.upcase}",
                                                                                   {}))
        end
        if env && @non_global_processed_options.any? && !hidden && !env_hidden
          affix = if counterpart
            " and `#{counterpart}` is passed."
          else
            "."
          end
          description += " Enabled by default if `$HOMEBREW_#{env.upcase}` is set#{affix}"
        end
        process_option(*names, description, type: :switch, hidden:, subcommands:) unless odisabled

        @parser.public_send(method, *names, *wrap_option_desc(description)) do |value|
          # This odeprecated should stick around indefinitely.
          replacement_string = replacement if replacement
          if odeprecated || odisabled
            odeprecated "the `#{names.first}` switch", replacement_string, disable: odisabled
          end
          value = true if names.none? { |name| name.start_with?("--[no-]") }

          set_switch(*names, value:, from: :args)
        end

        names.each do |name|
          set_constraints(name, depends_on:, subcommands:)
        end

        env_value = value_for_env(env)
        value = env_value&.present?
        set_switch(*names, value:, from: :env) unless value.nil?
      end
      alias switch_option switch

      sig { params(text: T.nilable(String)).returns(T.nilable(String)) }
      def description(text = nil)
        return @description if text.blank?

        @description = text.chomp
      end

      sig { params(text: String).void }
      def usage_banner(text)
        banner, description = text.chomp.split("\n\n", 2)

        if @current_subcommands.present?
          subcommand_description = description
          if subcommand_description.blank?
            usage_banner_lines = text.chomp.lines
            subcommand_description = usage_banner_lines.drop(1).join if usage_banner_lines.size > 1
          end

          @current_subcommands.each do |subcommand_name|
            subcommand = subcommand_for_name(subcommand_name)
            raise ArgumentError, "unknown subcommand: #{subcommand_name}" if subcommand.nil?

            subcommand.usage_banner = text.chomp
            next if subcommand.description.present? || subcommand_description.blank?

            subcommand.description = subcommand_description.lines.first&.chomp
          end
          return
        end

        @usage_banner = banner
        @description = description
      end

      sig { returns(T.nilable(String)) }
      def usage_banner_text = @parser.banner

      sig { returns(T.nilable(String)) }
      def root_usage_banner_text = @usage_banner

      sig { returns(ArgType) }
      def named_args_type
        return @named_args_type if @subcommands.empty?

        subcommand_names
      end

      sig {
        params(name: String, description: T.nilable(String), hidden: T::Boolean,
               subcommands: T.nilable(T.any(String, T::Array[String]))).void
      }
      def comma_array(name, description: nil, hidden: false, subcommands: nil)
        name = name.chomp "="
        description = option_description(description, name, hidden:)
        process_option(name, description, type: :comma_array, hidden:, subcommands:)
        @parser.on(name, OptionParser::REQUIRED_ARGUMENT, Array, *wrap_option_desc(description)) do |list|
          option_name = option_to_name(name)
          @option_sources[option_name] = :args
          @option_types[option_name] ||= :comma_array
          set_args_method(option_name.to_sym, list)
        end
      end

      sig {
        params(names: String, description: T.nilable(String), replacement: T.nilable(T.any(Symbol, String)),
               depends_on: T.nilable(String), hidden: T::Boolean, odeprecated: T::Boolean, odisabled: T::Boolean,
               subcommands: T.nilable(T.any(String, T::Array[String]))).void
      }
      def flag(*names, description: nil, replacement: nil, depends_on: nil, hidden: false, odeprecated: false,
               odisabled: false, subcommands: nil)
        required, flag_type = if names.any? { |name| name.end_with? "=" }
          [OptionParser::REQUIRED_ARGUMENT, :required_flag]
        else
          [OptionParser::OPTIONAL_ARGUMENT, :optional_flag]
        end
        names.map! { |name| name.chomp "=" }
        hidden = true if odeprecated || odisabled
        description = option_description(description, *names, hidden:)
        if odisabled
          description += " (disabled#{"; replaced by #{replacement}" if replacement.present?})"
        else
          process_option(*names, description, type: flag_type, hidden:, subcommands:)
        end
        @parser.on(*names, *wrap_option_desc(description), required) do |option_value|
          # This odisabled should stick around indefinitely.
          odeprecated "the `#{names.first}` flag", replacement, disable: odisabled if odeprecated || odisabled
          names.each do |name|
            option_name = option_to_name(name)
            @option_sources[option_name] = :args
            @option_types[option_name] ||= flag_type
            set_args_method(option_name.to_sym, option_value)
          end
        end

        names.each do |name|
          set_constraints(name, depends_on:, subcommands:)
        end
      end

      sig { params(name: Symbol, value: T.untyped).void }
      def set_args_method(name, value)
        @args.set_arg(name, value)
        return if @args.respond_to?(name)

        @args.define_singleton_method(name) do
          # We cannot reference the ivar directly due to https://github.com/sorbet/sorbet/issues/8106
          instance_variable_get(:@table).fetch(name)
        end
      end

      sig { params(options: String).returns(T::Array[T::Array[String]]) }
      def conflicts(*options)
        return @conflicts if options.empty?

        @conflicts << options.map { |option| option_to_name(option) }
      end

      sig { params(option: String).returns(String) }
      def option_to_name(option) = self.class.option_to_name(option)

      sig { params(name: String).returns(String) }
      def name_to_option(name)
        if name.length == 1
          "-#{name}"
        else
          "--#{name.tr("_", "-")}"
        end
      end

      sig { params(names: String).returns(T.nilable(String)) }
      def option_to_description(*names)
        names.map { |name| name.to_s.sub(/\A--?/, "").tr("-", " ") }.max
      end

      sig { params(description: T.nilable(String), names: String, hidden: T::Boolean).returns(String) }
      def option_description(description, *names, hidden: false)
        return HIDDEN_DESC_PLACEHOLDER if hidden
        return description if description.present?

        option_to_description(*names)
      end

      sig {
        params(argv: T::Array[String], ignore_invalid_options: T::Boolean)
          .returns([T::Array[String], T::Array[String]])
      }
      def parse_remaining(argv, ignore_invalid_options: false)
        i = 0
        remaining = []

        argv, non_options = split_non_options(argv)
        allow_commands = Array(@named_args_type).include?(:command)

        while i < argv.count
          begin
            begin
              arg = argv[i]

              remaining << arg unless @parser.parse([arg]).empty?
            rescue OptionParser::MissingArgument
              raise if i + 1 >= argv.count

              args = argv[i..(i + 1)]
              @parser.parse(args)
              i += 1
            end
          rescue OptionParser::InvalidOption
            if ignore_invalid_options || (allow_commands && arg && Commands.path(arg))
              remaining << arg
            else
              $stderr.puts generate_help_text
              raise
            end
          end

          i += 1
        end

        [remaining, non_options]
      end

      sig { params(argv: T::Array[String], ignore_invalid_options: T::Boolean).returns(Args) }
      def parse(argv = ARGV.freeze, ignore_invalid_options: false)
        raise "Arguments were already parsed!" if @args_parsed

        # If we accept formula options, but the command isn't scoped only
        # to casks, parse once allowing invalid options so we can get the
        # remaining list containing formula names.
        if @formula_options && !only_casks?(argv)
          remaining, non_options = parse_remaining(argv, ignore_invalid_options: true)

          argv = [*remaining, "--", *non_options]

          formulae(argv).each do |f|
            next if f.options.empty?

            f.options.each do |o|
              name = o.flag
              description = "`#{f.name}`: #{o.description}"
              if name.end_with? "="
                flag(name, description:)
              else
                switch name, description:
              end

              conflicts "--cask", name
            end
          end
        end

        remaining, non_options = parse_remaining(argv, ignore_invalid_options:)

        named_args = if ignore_invalid_options
          []
        else
          remaining + non_options
        end

        unless ignore_invalid_options
          if @subcommands.present? && named_args.present?
            subcommand_arg = named_args.fetch(0)
            if (subcommand = subcommand_for_name(subcommand_arg)) && subcommand.alias_options.key?(subcommand_arg)
              set_switch(subcommand.alias_options.fetch(subcommand_arg), value: true, from: :args)
            end
          end
          unless @is_dev_cmd
            set_default_options
            validate_options
          end
          check_constraint_violations(named_args)
          check_named_args(named_args)
          check_subcommand_violations(named_args)
        end

        if @subcommands.present?
          parsed_subcommand = subcommand_name(named_args)
          # This odeprecated should stick around indefinitely.
          if parsed_subcommand && (subcommand = subcommand_for_name(parsed_subcommand)) &&
             (subcommand.odeprecated || subcommand.odisabled)
            odeprecated "the `#{subcommand.name}` subcommand", subcommand.replacement,
                        disable: subcommand.odisabled
          end
          set_args_method(:subcommand, parsed_subcommand)
          named_args = if parsed_subcommand && named_args.present?
            named_args.drop(1)
          else
            []
          end
        end
        @args.freeze_named_args!(named_args, cask_options: @cask_options, without_api: @named_args_without_api)
        remaining_args = if non_options.empty?
          remaining
        else
          [*remaining, "--", non_options]
        end
        @args.freeze_remaining_args!(remaining_args)
        @args.freeze_processed_options!(@processed_options)
        @args.freeze

        @args_parsed = T.let(true, T.nilable(TrueClass))

        if !ignore_invalid_options && @args.help?
          puts generate_help_text(remaining_args: @subcommands.present? ? remaining : nil)
          exit
        end

        @args
      end

      sig { void }
      def set_default_options; end

      sig { void }
      def validate_options; end

      sig { params(remaining_args: T.nilable(T::Array[String])).returns(String) }
      def generate_help_text(remaining_args: nil)
        help_text = if remaining_args.nil? || @subcommands.empty?
          @parser.to_s
        elsif (subcommand = remaining_args.filter_map do |arg|
          subcommand_for_name(arg) unless arg.start_with?("-")
        end.first)
          parts = T.let([], T::Array[String])
          parts << (subcommand.usage_banner || "`#{@command_name} #{subcommand.name}`").sub(/\A`brew /, "`")
          option_summaries = option_summaries_text(subcommand.name)
          parts << option_summaries if option_summaries.present?
          parts.join("\n\n")
        else
          parts = T.let([], T::Array[String])
          usage_banner = @usage_banner
          description = @description
          parts << usage_banner if usage_banner.present?
          parts << description if description.present?

          subcommand_lines = @subcommands.filter_map do |subcommand|
            next if subcommand.hidden

            subcommand_summary = if (usage_banner = subcommand.usage_banner)
              usage_banner.lines.drop(1).map(&:strip).find(&:present?)
            end
            subcommand_summary ||= subcommand.description
            if subcommand_summary.present?
              "  `#{subcommand.name}`: #{subcommand_summary}"
            else
              "  `#{subcommand.name}`"
            end
          end
          parts << "Subcommands:\n#{subcommand_lines.join("\n")}"

          option_summaries = option_summaries_text(nil)
          parts << option_summaries if option_summaries.present?
          parts.join("\n\n")
        end

        Formatter.format_help_text(help_text, width: Formatter::COMMAND_DESC_WIDTH)
                 .gsub(/\n.*?@@HIDDEN@@.*?(?=\n)/, "")
                 .sub(/^/, "#{Tty.bold}Usage: brew#{Tty.reset} ")
                 .gsub(/`(.*?)`/m, "#{Tty.bold}\\1#{Tty.reset}")
                 .gsub(%r{<([^\s]+?://[^\s]+?)>}) { |url| Formatter.url(url) }
                 .gsub(/\*(.*?)\*|<(.*?)>/m) do |underlined|
                   underlined[1...-1].to_s.gsub(/^(\s*)(.*?)$/, "\\1#{Tty.underline}\\2#{Tty.reset}")
                 end
      end

      sig { void }
      def cask_options
        self.class.global_cask_options.each do |args|
          options = T.cast(args.pop, T::Hash[Symbol, String])
          send(*args, **options)
          conflicts "--formula", args[1]
        end
        @cask_options = true
      end

      sig { void }
      def formula_options
        @formula_options = true
      end

      sig {
        params(
          type:        ArgType,
          number:      T.nilable(Integer),
          min:         T.nilable(Integer),
          max:         T.nilable(Integer),
          without_api: T::Boolean,
        ).void
      }
      def named_args(type = nil, number: nil, min: nil, max: nil, without_api: false)
        raise ArgumentError, "Do not specify both `number` and `min` or `max`" if number && (min || max)

        if type == :none && (number || min || max)
          raise ArgumentError, "Do not specify both `number`, `min` or `max` with `named_args :none`"
        end

        if @current_subcommands.present?
          @current_subcommands.each do |subcommand_name|
            subcommand = subcommand_for_name(subcommand_name)
            raise ArgumentError, "unknown subcommand: #{subcommand_name}" if subcommand.nil?

            subcommand.named_args_type = type
            if type == :none
              subcommand.max_named_args = 0
            elsif number
              subcommand.min_named_args = subcommand.max_named_args = number
            elsif min || max
              subcommand.min_named_args = min
              subcommand.max_named_args = max
            end
            subcommand.named_args_without_api = without_api
          end
          return
        end

        @named_args_type = type

        if type == :none
          @max_named_args = 0
        elsif number
          @min_named_args = @max_named_args = number
        elsif min || max
          @min_named_args = min
          @max_named_args = max
        end

        @named_args_without_api = without_api
      end

      sig { void }
      def hide_from_man_page!
        @hide_from_man_page = true
      end

      sig {
        params(
          name:          String,
          aliases:       T::Array[String],
          alias_options: T::Hash[String, String],
          description:   T.nilable(String),
          default:       T::Boolean,
          hidden:        T::Boolean,
          replacement:   T.nilable(T.any(String, Symbol)),
          odeprecated:   T::Boolean,
          odisabled:     T::Boolean,
          block:         T.nilable(T.proc.bind(Parser).void),
        ).void
      }
      def subcommand(name, aliases: [], alias_options: {}, description: nil, default: false, hidden: false,
                     replacement: nil, odeprecated: false, odisabled: false, &block)
        previous_subcommands = @current_subcommands
        hidden = true if odeprecated || odisabled

        @subcommands << Subcommand.new(
          name:,
          aliases:       aliases | alias_options.keys,
          alias_options:,
          description:,
          default:,
          hidden:,
          replacement:,
          odeprecated:,
          odisabled:,
        )

        @current_subcommands = [name]
        instance_eval(&block) if block
      ensure
        @current_subcommands = previous_subcommands
      end

      sig { returns(T::Array[String]) }
      def subcommand_names = @subcommands.map(&:name)

      sig { returns(T.nilable(Subcommand)) }
      def default_subcommand = @subcommands.find(&:default)

      sig { params(name: String).returns(T.nilable(Subcommand)) }
      def subcommand_for_name(name)
        @subcommands.find { |subcommand| subcommand.name == name || subcommand.aliases.include?(name) }
      end

      sig { params(subcommand_name: T.nilable(String)).returns(Args::OptionsType) }
      def processed_options_for_subcommand(subcommand_name)
        subcommand = if subcommand_name
          subcommand_for_name(subcommand_name)
        else
          default_subcommand
        end
        canonical_subcommand = subcommand&.name

        root_options = @processed_options_by_subcommand.fetch(nil, [])
        return root_options if canonical_subcommand.nil?

        root_options + @processed_options_by_subcommand.fetch(canonical_subcommand, [])
      end

      sig { returns(Args::OptionsType) }
      def processed_options_for_root_command
        @processed_options_by_subcommand.fetch(nil, [])
      end

      sig { params(subcommand_name: String).returns(ArgType) }
      def named_args_type_for_subcommand(subcommand_name)
        subcommand_for_name(subcommand_name)&.named_args_type
      end

      sig { params(named_args: T::Array[String]).returns(T.nilable(String)) }
      def subcommand_name(named_args)
        subcommand = if named_args.empty?
          default_subcommand
        else
          subcommand_for_name(named_args.fetch(0))
        end

        subcommand&.name
      end

      sig { params(option: String).returns(T::Array[String]) }
      def subcommands_for_option(option)
        @option_subcommands.fetch(option_to_name(option), [])
      end

      private

      sig { returns(String) }
      def generate_usage_banner
        command_names = ["`#{@command_name}`"]
        aliases_to_skip = %w[instal uninstal]
        command_names += Commands::HOMEBREW_INTERNAL_COMMAND_ALIASES.filter_map do |command_alias, command|
          next if aliases_to_skip.include? command_alias

          "`#{command_alias}`" if command == @command_name
        end.sort

        options = if @non_global_processed_options.empty?
          ""
        elsif @non_global_processed_options.count > 2
          " [<options>]"
        else
          required_argument_types = [:required_flag, :comma_array]
          @non_global_processed_options.map do |option, type|
            next " [`#{option}=`]" if required_argument_types.include? type

            " [`#{option}`]"
          end.join
        end

        named_args = ""
        if @named_args_type.present? && @named_args_type != :none
          arg_type = if @named_args_type.is_a? Array
            types = @named_args_type.filter_map do |type|
              next unless type.is_a? Symbol
              next SYMBOL_TO_USAGE_MAPPING[type] if SYMBOL_TO_USAGE_MAPPING.key?(type)

              "<#{type}>"
            end
            types << "<subcommand>" if @named_args_type.any?(String)
            types.join("|")
          elsif SYMBOL_TO_USAGE_MAPPING.key? @named_args_type
            SYMBOL_TO_USAGE_MAPPING[@named_args_type]
          else
            "<#{@named_args_type}>"
          end

          named_args = if @min_named_args.nil? && @max_named_args == 1
            " [#{arg_type}]"
          elsif @min_named_args.nil?
            " [#{arg_type} ...]"
          elsif @min_named_args == 1 && @max_named_args == 1
            " #{arg_type}"
          elsif @min_named_args == 1
            " #{arg_type} [...]"
          else
            " #{arg_type} ..."
          end
        end

        "#{command_names.join(", ")}#{options}#{named_args}"
      end

      sig { returns(String) }
      def generate_banner
        @usage_banner ||= generate_usage_banner

        @parser.banner = <<~BANNER
          #{@usage_banner}

          #{usage_description_text}

        BANNER
      end

      sig { params(names: String, value: T.untyped, from: Symbol).void }
      def set_switch(*names, value:, from:)
        names.each do |name|
          option_name = option_to_name(name)
          @switch_sources[option_name] = from
          @option_sources[option_name] = from
          @option_types[option_name] ||= :switch
          set_args_method(:"#{option_name}?", value)
        end
      end

      sig { params(args: String).void }
      def disable_switch(*args)
        args.each do |name|
          result = if name.start_with?("--[no-]")
            nil
          else
            false
          end
          set_args_method(:"#{option_to_name(name)}?", result)
        end
      end

      sig { params(name: String).returns(T::Boolean) }
      def option_passed?(name)
        [name.to_sym, :"#{name}?"].any? do |method|
          @args.public_send(method) if @args.respond_to?(method)
        end
      end

      sig { params(desc: String).returns(T::Array[String]) }
      def wrap_option_desc(desc)
        Formatter.format_help_text(desc, width: Formatter::OPTION_DESC_WIDTH).split("\n")
      end

      sig {
        params(name: String, depends_on: T.nilable(String),
               subcommands: T.nilable(T.any(String, T::Array[String]))).void
      }
      def set_constraints(name, depends_on:, subcommands:)
        return if depends_on.nil?

        primary = option_to_name(depends_on)
        secondary = option_to_name(name)
        @constraints << [primary, secondary, effective_subcommands(subcommands)]
      end

      sig { params(args: T::Array[String]).void }
      def check_constraints(args)
        subcommand = subcommand_name(args)
        @constraints.each do |primary, secondary, subcommands|
          next if subcommands.present? && (subcommand.nil? || subcommands.exclude?(subcommand))

          primary_passed = option_passed?(primary)
          secondary_passed = option_passed?(secondary)

          next if !secondary_passed || (primary_passed && secondary_passed)

          primary = name_to_option(primary)
          secondary = name_to_option(secondary)

          raise OptionConstraintError.new(primary, secondary, missing: true)
        end
      end

      sig { void }
      def check_conflicts
        @conflicts.each do |mutually_exclusive_options_group|
          violations = mutually_exclusive_options_group.select do |option|
            option_passed? option
          end

          next if violations.count < 2

          env_var_options = violations.select do |option|
            @switch_sources[option_to_name(option)] == :env
          end

          select_cli_arg = violations.count - env_var_options.count == 1
          raise OptionConflictError, violations.map { name_to_option(it) } unless select_cli_arg

          env_var_options.each { disable_switch(it) }
        end
      end

      sig { void }
      def check_invalid_constraints
        @conflicts.each do |mutually_exclusive_options_group|
          @constraints.each do |p, s, _subcommands|
            next unless Set[p, s].subset?(Set[*mutually_exclusive_options_group])

            raise InvalidConstraintError.new(p, s)
          end
        end
      end

      sig { params(args: T::Array[String]).void }
      def check_constraint_violations(args)
        check_invalid_constraints
        check_conflicts
        check_constraints(args)
      end

      sig { params(args: T::Array[String], type: ArgType, min: T.nilable(Integer), max: T.nilable(Integer)).void }
      def check_named_args_count(args, type, min, max)
        types = Array(type).filter_map do |type|
          next type if type.is_a? Symbol

          :subcommand
        end.uniq

        exception = if min && max && min == max && args.size != max
          NumberOfNamedArgumentsError.new(min, types:)
        elsif min && args.size < min
          MinNamedArgumentsError.new(min, types:)
        elsif max && args.size > max
          MaxNamedArgumentsError.new(max, types:)
        end

        raise exception if exception
      end

      sig { params(args: T::Array[String]).void }
      def check_named_args(args)
        check_named_args_count(args, @named_args_type, @min_named_args, @max_named_args)
      end

      sig { params(args: T::Array[String]).void }
      def check_subcommand_violations(args)
        return if @subcommands.empty?

        subcommand = if args.empty?
          default_subcommand
        else
          subcommand_for_name(args.fetch(0))
        end
        raise UsageError, "unknown subcommand: `#{args.first}`" if subcommand.nil? && args.present?
        return if subcommand.nil?

        subcommand_args = if args.empty?
          args
        else
          args.drop(1)
        end
        check_named_args_count(subcommand_args, subcommand.named_args_type, subcommand.min_named_args,
                               subcommand.max_named_args)
        @option_sources.each do |option, source|
          next if source == :env
          next if option_allowed_for_subcommand?(option, subcommand.name)

          option_type = @option_types.fetch(option)
          option_type_name = if option_type == :switch
            "switch"
          else
            "flag"
          end
          raise UsageError, "The `#{subcommand.name}` subcommand does not accept the `#{name_to_option(option)}` " \
                            "#{option_type_name}."
        end
      end

      sig { returns(String) }
      def usage_description_text
        parts = T.let([], T::Array[String])
        parts << @description if @description.present?
        @subcommands.each do |subcommand|
          usage_banner = subcommand.usage_banner
          parts << usage_banner if usage_banner.present?
        end
        parts.join("\n\n")
      end

      sig { params(subcommand_name: T.nilable(String)).returns(String) }
      def option_summaries_text(subcommand_name)
        lines = T.let([], T::Array[String])
        short_options = T.let({}, T::Hash[String, T::Boolean])
        long_options = T.let({}, T::Hash[String, T::Boolean])

        processed_option_summaries = @processed_option_summaries_by_subcommand.fetch(nil, [])
        if subcommand_name.present?
          processed_option_summaries += @processed_option_summaries_by_subcommand.fetch(subcommand_name, [])
        end

        processed_option_summaries.each do |option, hidden|
          next if hidden

          option.summarize(short_options, long_options, @parser.summary_width, @parser.summary_width - 1,
                           @parser.summary_indent) { |line| lines << line }
        end

        lines.join("\n")
      end

      sig { params(option: String, subcommand_name: T.nilable(String)).returns(T::Boolean) }
      def option_allowed_for_subcommand?(option, subcommand_name)
        subcommands = @option_subcommands[option]
        return true if subcommands.blank?

        subcommand_name.present? && subcommands.include?(subcommand_name)
      end

      sig { params(subcommands: T.nilable(T.any(String, T::Array[String]))).returns(T.nilable(T::Array[String])) }
      def effective_subcommands(subcommands)
        return @current_subcommands if subcommands.nil?

        Array(subcommands).map do |subcommand|
          subcommand_for_name(subcommand)&.name || subcommand
        end
      end

      sig {
        params(option_names: T::Array[String], type: Symbol,
               subcommands: T.nilable(T.any(String, T::Array[String]))).void
      }
      def record_option_metadata(option_names, type:, subcommands:)
        option_names.each do |name|
          option_name = option_to_name(name)
          @option_types[option_name] = type
          # Global options are accepted everywhere, so a subcommand block
          # re-declaring one (e.g. for a custom description) must not constrain it.
          next if global_option?(name)

          effective_subcommands = effective_subcommands(subcommands)
          next if effective_subcommands.blank?

          @option_subcommands[option_name] = (@option_subcommands[option_name] || []) |
                                             effective_subcommands
        end
      end

      sig { params(name: String).returns(T::Boolean) }
      def global_option?(name)
        option_name = option_to_name(name)
        self.class.global_options.any? do |short, long, _desc|
          option_to_name(short) == option_name || option_to_name(long) == option_name
        end
      end

      sig {
        params(args: String, type: Symbol, hidden: T::Boolean,
               subcommands: T.nilable(T.any(String, T::Array[String]))).void
      }
      def process_option(*args, type:, hidden: false, subcommands: nil)
        option, = @parser.make_switch(args)
        @processed_options.reject! { |existing| existing.second == option.long.first } if option.long.first.present?
        if option.long.first.present?
          @processed_option_summaries.reject! do |existing,|
            existing.long.first == option.long.first
          end
        end
        @processed_options << [option.short.first, option.long.first, option.desc.first, hidden]
        @processed_option_summaries << [option, hidden]

        display_subcommands = effective_subcommands(subcommands)
        subcommand_names = T.let([], T::Array[T.nilable(String)])
        if display_subcommands.blank?
          subcommand_names << nil
        else
          subcommand_names.concat(display_subcommands)
        end

        subcommand_names.each do |subcommand_name|
          processed_options = @processed_options_by_subcommand[subcommand_name] ||= []
          processed_options.reject! { |existing| existing.second == option.long.first } if option.long.first.present?
          processed_options << [option.short.first, option.long.first, option.desc.first, hidden]

          processed_option_summaries = @processed_option_summaries_by_subcommand[subcommand_name] ||= []
          if option.long.first.present?
            processed_option_summaries.reject! { |existing,| existing.long.first == option.long.first }
          end
          processed_option_summaries << [option, hidden]
        end

        args.pop # last argument is the description
        record_option_metadata(args, type:, subcommands:)
        if type == :switch
          disable_switch(*args)
        else
          args.each do |name|
            set_args_method(option_to_name(name).to_sym, nil)
          end
        end

        return if hidden
        return if self.class.global_options.include? [option.short.first, option.long.first, option.desc.first]

        @non_global_processed_options << [option.long.first || option.short.first, type]
      end

      sig { params(argv: T::Array[String]).returns([T::Array[String], T::Array[String]]) }
      def split_non_options(argv)
        if (sep = argv.index("--"))
          [argv.take(sep), argv.drop(sep + 1)]
        else
          [argv, []]
        end
      end

      sig { params(argv: T::Array[String]).returns(T::Array[Formula]) }
      def formulae(argv)
        argv, non_options = split_non_options(argv)

        named_args = argv.reject { |arg| arg.start_with?("-") } + non_options
        spec = if argv.include?("--HEAD")
          :head
        else
          :stable
        end

        # Only lowercase names, not paths, bottle filenames or URLs
        named_args.filter_map do |arg|
          next if arg.match?(HOMEBREW_CASK_TAP_CASK_REGEX)

          begin
            Formulary.factory(arg, spec, flags: argv.select { |a| a.start_with?("--") })
          rescue FormulaUnavailableError, FormulaSpecificationError
            nil
          end
        end.uniq(&:name)
      end

      sig { params(argv: T::Array[String]).returns(T::Boolean) }
      def only_casks?(argv)
        argv.include?("--casks") || argv.include?("--cask")
      end

      sig { params(env: T.nilable(T.any(String, Symbol))).returns(T.untyped) }
      def value_for_env(env)
        return if env.blank?

        method_name = :"#{env}?"
        if Homebrew::EnvConfig.respond_to?(method_name)
          Homebrew::EnvConfig.public_send(method_name)
        else
          ENV.fetch("HOMEBREW_#{env.upcase}", nil)
        end
      end
    end
  end
end
