#!/usr/bin/env ruby
# frozen_string_literal: true

require_relative 'teamcity_github'

TEAMCITY_BUILD_ID = ENV['TEAMCITY_BUILD_ID']
TEAMCITY_BUILD_TYPE_ID = ENV['TEAMCITY_BUILD_TYPE_ID']
BUILD_NUMBER = ENV['BUILD_NUMBER']

BRANCH = ENV['BRANCH']
REPO = 'twilight/twilight'

SUBDOMAIN_URL_SUFFIX_MAP = {
  clips: '/ProductiveUglyVanillaMingLee',
  player: '/?channel=bufferbunny',
}

sites_json = JSON.parse(File.read('sites.json'))
default_site = sites_json['defaultSite']
sub_sites = sites_json['sites'].keys.reject { |s| s == default_site }.map do |site|
  url = site.gsub('.twitch.tv',"-#{BRANCH}.twitch.tech")
  suffix = SUBDOMAIN_URL_SUFFIX_MAP[site.split('.')[0].to_sym]

  "#{url}#{suffix}"
end

def print_sub_sites(ss)
  out = ''
  ss.each do |s|
    out += "- [https://#{s}](https://#{s})\n"
  end
  out
end

url = "https://#{BRANCH}.twitch.tech/"
build_link = "https://teamcity.internal.justin.tv/viewLog.html?buildId=#{TEAMCITY_BUILD_ID}&buildTypeId=#{TEAMCITY_BUILD_TYPE_ID}"
tagline = 'BrowserClients :: twilight :: twilight-pr :: Deploy to Test Environment'

message = <<~MSG
  Build is available at [#{url}](#{url})
  ### Available subsites
  #{print_sub_sites(sub_sites)}
  ### Desktop
  - `twitch://ui-url/#{url}`\n
  *Desktop developers may point their app at this PR by pasting the link above into a browser (Desklight only)*\n\n
  #{tagline} :: [#{BUILD_NUMBER}](#{build_link})
MSG

comment = CSITeamCity::GitHub::Comment.new(message, repo: REPO, on: BRANCH)
comment.update_or_create(tagline)
