# frozen_string_literal: true

require 'rubygems'
require 'bundler'
Bundler.setup

Bundler::GemHelper.install_tasks

if RUBY_ENGINE == 'ruby' && Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('3.3')
  require_relative 'script/release_preparation'
  require 'ruby-gem-release/workflow/ruby_gem'

  workflow = RubyGemRelease::Workflow::RubyGem.new(
    version: RubyGemRelease::Version::RubyConstant.new(path: 'lib/hashie/version.rb', constant: 'VERSION'),
    changelog: RubyGemRelease::Changelog::KeepAChangelog.new
  )
  preparation = HashieReleasePreparation.new
  workflow.before(:validate) { |ctx| preparation.validate!(ctx.release, changelog: ctx.workflow.changelog) }
  workflow.before(:prepare_release) { |ctx| preparation.prepare!(ctx.release, changelog: ctx.workflow.changelog) }
  workflow.after(:prepare_next) { |ctx| preparation.prepare_next!(ctx.release) }
  workflow.install_tasks
end

require 'rspec/core/rake_task'
RSpec::Core::RakeTask.new do |spec|
  spec.pattern = 'spec/**/*_spec.rb'
  spec.exclude_pattern = 'spec/integration/**/*_spec.rb'
end

namespace :docs do
  desc 'Validate executable YARD examples and public API documentation coverage'
  task :examples do
    ruby '-Ilib', 'script/test_documentation_examples.rb'
  end

  desc 'Validate every README Ruby example with the isolated documentation bundle'
  task :readme do
    Bundler.with_unbundled_env do
      sh({ 'BUNDLE_GEMFILE' => 'spec/documentation/Gemfile' }, 'bundle', 'exec', 'ruby', '-Ilib', 'script/test_readme_examples.rb')
    end
  end
end

require 'rubocop/rake_task'
RuboCop::RakeTask.new(:rubocop)
if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('3.2')
  RuboCop::RakeTask.new(:rubocop_exception_messages) do |task|
    task.patterns = ['lib/**/*.rb', 'spec/**/*.rb']
    task.options = [
      '--only',
      'ExceptionMessages/Casing,ExceptionMessages/Punctuation,' \
      'ExceptionMessages/QuoteStyle,ExceptionMessages/RedundantExceptionName'
    ]
  end
  Rake::Task[:rubocop].enhance([:rubocop_exception_messages])
end

require_relative 'spec/support/integration_specs'
desc 'Install integration dependencies and run integration specs'
task :integration_specs do
  next if ENV['CI']

  status_codes = []
  handler = lambda do |status_code|
    status_codes << status_code unless status_code.zero?
  end

  run_all_integration_specs(handler: handler, logger: ->(msg) { puts msg })

  if status_codes.any?
    warn "#{status_codes.size} integration test(s) failed"
    exit status_codes.last
  end
end

default_tasks = %i[spec integration_specs]
default_tasks.unshift(:rubocop) if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('3.2')
task default: default_tasks
