#!/usr/bin/env ruby
# Copyright (c) HashiCorp, Inc.
# SPDX-License-Identifier: BUSL-1.1


require 'yaml'
require 'pp'

require_relative 'get_github_prs'
#
# Make sure we know what repos we are looking at
#

$repos = YAML.load File.read("scripts/tfe-releases/app_repos.yaml")

#
# Make sure we know what releases we are comparing
#

from = ENV["FROM"]
raise "specify the previous release with FROM=" unless from

to = ENV['TO']
raise "specify the current release with TO=" unless to

#
# Create Arrays to collect results
#

$customer_impacting_changelog_lines = []
$non_customer_impacting_changelog_lines = []

class Changelog
  def initialize(repo, from, to)
    @repo = repo
    @from = from
    @to = to
  end

  def generate
    prs = PullRequest.new(@repo, @from, @to).generate

    # Print changelog lines that have customer impact
    collect_customer_impact(prs)

    # Print changelog lines that have no customer impact
    collect_no_impact(prs)
  end

  def collect_customer_impact(prs)
    prs.each do |pr|
      # Do not include PRs with no-impact changelog lines
      next if pr.body.nil?
      next if pr.body.match(/CHANGELOG: no-impact/)

      # Include PRs with real changelog lines
      pr.body.match(/CHANGELOG:(.+)$/) do |match|
        $customer_impacting_changelog_lines << format_line(match[1].to_s, pr)
      end
    end
  end

  def collect_no_impact(prs)
    prs.each do |pr|
      # Include PRs with no-impact changelog lines
      !pr.body.nil? && pr.body.match(/CHANGELOG: no-impact/) do |match|
        $non_customer_impacting_changelog_lines << format_line(pr.title, pr)
      end

      # Do not include PRs with real changelog lines
      next if !pr.body.nil? && pr.body.match(/CHANGELOG:(.+)$/)

      # Include PRs with no changelog lines
      $non_customer_impacting_changelog_lines << format_line(pr.title, pr)
    end
  end

  def format_line(message, pr)
    author = "-- **@#{pr.user.login}**"
    link = "[#{@repo}##{pr.number}](https://github.com/hashicorp/#{@repo}/pull/#{pr.number})"

    ["1.", message.strip, author, link].join(" ")
  end
end

$repos.each do |repo|
  Changelog.new(repo, from, to).generate
end

puts <<-HEREDOC

### Generated Changelog

The changelog below was generated by `scripts/changelog.rb`. It includes PRs merged from each repository in `app_repos.yaml`. The purpose of this generated changelog is to serve as starting place for constructing the customer facing changelog above.

#### Possible Customer Impacting Changes

These PRs included a changelog line the PR body. This changelog line has been used as the message below.

#{$customer_impacting_changelog_lines.join("\n")}

#### Possible Non Customer Facing Changes

These PRs did not include a changelog line in the PR body. The PR title has been used as the message below.

#{$non_customer_impacting_changelog_lines.join("\n")}

HEREDOC
