# frozen_string_literal: true

# While you're here, handy tip for debugging: try to attach @announce-output
# @announce-command to the scenarios/features to see what's going on

require "bundler"
Bundler.setup
require "capybara/cucumber"
require "capybara/cuprite"
require "aruba/cucumber"
require "aruba/config/jruby" if RUBY_ENGINE == "jruby"
require "simplecov"

# Monkey-patching Capybara::DSL if Capybara::DSLRSpecProxyInstaller has no `extended` hook
unless Module.new.extend(RSpec::Matchers).extend(Capybara::DSL).singleton_class.ancestors.include?(Capybara::RSpecMatcherProxies)
  Capybara::DSL.extend(Module.new do
    def extended(base)
      base.extend(Capybara::RSpecMatcherProxies) if defined?(RSpec::Matchers) && base.is_a?(RSpec::Matchers)
      super
    end
  end)
end

# Rack app for Capybara which returns the latest coverage report from Aruba temp project dir
coverage_dir = File.expand_path("../../tmp/aruba/project/coverage/", __dir__)

# Prevent the browser from caching coverage_data.js between scenario visits
class NoCacheMiddleware
  def initialize(app)
    @app = app
  end

  def call(env)
    status, headers, body = @app.call(env)
    headers["cache-control"] = "no-store"
    [status, headers, body]
  end
end

Capybara.app = Rack::Builder.new do
  use NoCacheMiddleware
  use Rack::Static, urls: {"/" => "index.html"}, root: coverage_dir
  run Rack::Directory.new(coverage_dir)
end.to_app

Capybara.configure do |config|
  config.ignore_hidden_elements = false
  config.server = :webrick
  config.default_driver = :cuprite
end

Before("@branch_coverage") do
  skip_this_scenario unless SimpleCov.branch_coverage_supported?
end

Before("@process_fork") do
  # Process.fork is NotImplementedError in jruby
  skip_this_scenario if jruby?
end

Before("@no_jruby") do
  skip_this_scenario if jruby?
end

def jruby?
  defined?(RUBY_ENGINE) && RUBY_ENGINE == "jruby"
end

Aruba.configure do |config|
  config.allow_absolute_paths = true

  # Per-command ceiling. The 20-second default was tight enough that
  # cold-cache `bundle exec rspec` / `bundle exec parallel_rspec` /
  # `bundle exec rake test` invocations in the test_projects features
  # (old_version_json, parallel_tests, test_unit_without_simplecov)
  # would occasionally time out and fail before the work even
  # finished, even though the same scenarios passed instantly on a
  # warm cache. `--retry 3 --no-strict-flaky` masked the failures
  # but blew the suite's wall time up by 10x or more on cold runs.
  # 60 seconds accommodates first-bundle-activation latency on slow
  # CI runners without slowing the happy path (timeout is a ceiling).
  config.exit_timeout = RUBY_ENGINE == "jruby" ? 120 : 60
end
