# frozen_string_literal: true

require './lib/semver_dialects/version'

GEMFILE_LOCK_VERSION_REGEX = /semver_dialects \((?<version>\d+\.\d+\.\d+)\)/
CHANGELOG_VERSION_REGEX = /## v(?<version>\d+\.\d+\.\d+)/

gemfile_lock = File.read('Gemfile.lock')
GEMFILE_LOCK_VERSION = gemfile_lock.match(GEMFILE_LOCK_VERSION_REGEX)['version']

changelog = File.read('CHANGELOG.md')
CHANGELOG_VERSION = changelog.match(CHANGELOG_VERSION_REGEX)['version']

if SemverDialects::VERSION != GEMFILE_LOCK_VERSION || SemverDialects::VERSION != CHANGELOG_VERSION
  puts 'Version drift detected between lib/semver_dialects/version.rb, Gemfile.lock, and CHANGELOG.md.'
  puts ''
  puts '1. Ensure that lib/semver_dialects/version.rb and CHANGELOG.md match'
  puts '2. Run `bundler lock`'
  puts '3. Commit and push the latest changes'
  exit 1
end

# Optional fourth check: when invoked with a tag (e.g. from the `publish gem` job on a
# tag pipeline), assert the tag matches the on-disk version. Skipped when called
# without an argument (e.g. from the `version verification` job on master).
tag = ARGV[0]
if tag && !tag.empty?
  expected_tag = "v#{SemverDialects::VERSION}"

  if tag != expected_tag
    puts "Tag/version mismatch: tag=#{tag} but lib/semver_dialects/version.rb declares #{expected_tag}."
    puts ''
    puts "The tag in CI_COMMIT_TAG (#{tag}) does not match the version in " \
         "lib/semver_dialects/version.rb (#{expected_tag})."
    puts 'To recover:'
    puts "  1. Delete the release and tag: glab release delete #{tag} --yes --with-tag"
    puts '  2. Update lib/semver_dialects/version.rb (and CHANGELOG.md, Gemfile.lock) to match the intended version,'
    puts '     or re-tag from a master commit whose version on disk matches the tag name.'
    puts '  3. Re-run the create_release skill to publish.'
    exit 1
  end
end
