# frozen_string_literal: true

require 'fileutils'

module GDK
  module Command
    class DebugInfo < BaseCommand
      NEW_ISSUE_LINK = 'https://gitlab.com/gitlab-org/gitlab-development-kit/-/issues/new'
      ENV_WILDCARDS = %w[GDK_.* BUNDLE_.* GEM_.*].freeze
      ENV_VARS = %w[
        PATH LANG LANGUAGE LC_ALL LDFLAGS CPPFLAGS PKG_CONFIG_PATH
        LIBPCREDIR RUBY_CONFIGURE_OPTS
      ].freeze

      def run(_ = [])
        GDK::Output.puts separator
        GDK::Output.info review_prompt
        GDK::Output.puts separator

        GDK::Output.puts "Operating system: #{os_name}"
        GDK::Output.puts "Architecture: #{arch}"
        GDK::Output.puts "Ruby version: #{ruby_version}"
        GDK::Output.puts "GDK version: #{gdk_version}"

        GDK::Output.puts
        GDK::Output.puts 'Environment:'

        environment_hash = ENV.each_with_object({}) do |(variable, value), result|
          next unless matches_regex?(variable)

          result[variable] = value
        end

        ConfigRedactor.redact(environment_hash.merge(env_vars)).each do |var, content|
          GDK::Output.puts "#{var}=#{content}"
        end

        if gdk_yml_exists?
          GDK::Output.puts
          GDK::Output.puts 'GDK configuration:'
          GDK::Output.puts gdk_yml
        end

        GDK::Output.puts separator

        true
      end

      def os_name
        shellout('uname -moprsv')
      end

      def arch
        shellout('arch')
      end

      def ruby_version
        shellout('ruby --version')
      end

      def node_version
        shellout('node --version')
      end

      def gdk_version
        shellout('git rev-parse --short HEAD', chdir: GDK.root)
      end

      def shellout(cmd, **args)
        Shellout.new(cmd, **args).run
      rescue StandardError => e
        "Unknown (#{e.message})"
      end

      def env_vars
        ENV_VARS.each_with_object({}) do |variable, result|
          result[variable] = ENV.fetch(variable, nil)&.gsub(Dir.home, '$HOME')
        end
      end

      def matches_regex?(var)
        var.match?(combined_env_regex)
      end

      def combined_env_regex
        @combined_env_regex ||= /^#{ENV_WILDCARDS.join('|')}$/
      end

      def gdk_yml
        ConfigRedactor.redact(GDK.config.dump!(user_only: true)).to_yaml
      end

      def gdk_yml_exists?
        File.exist?(GDK::Config::FILE)
      end

      def review_prompt
        <<~MESSAGE
          Please review the content below, ensuring any sensitive information such as
             API keys, passwords etc are removed before submitting. To create an issue
             in the GitLab Development Kit project, use the following link:

             #{NEW_ISSUE_LINK}

        MESSAGE
      end

      def separator
        @separator ||= '-' * 80
      end
    end
  end
end
