#!/usr/bin/env bash
set -euo pipefail
source "$SHELLOPS_DIR/.envrc"

:<<'DOC'
Posts a Blizz comment on a PR asking for Linear issue references.

Pre-fills with any issue ID detected in the head branch name
(e.g. jeff/ops-82-some-description -> OPS-82).

Skips if Blizz has already posted a prompt comment on this PR.
DOC

import \
  "$SHELLOPS_DIR/lib/forgejo.api.sh" \
  "$SHELLOPS_DIR/lib/manifest.api.sh"

__prompt_refs__MARKER="<!-- blizz:linear-prompt -->"

function main() {
  local pr_number token options body

  pr_number="${CI_COMMIT_PULL_REQUEST:-}"
  [[ -z "$pr_number" ]] && pr_number="$(detect_pr_number)"

  if [[ -z "$pr_number" ]]; then
    error "No PR number available. Is this running in a PR pipeline?"
    exit 1
  fi

  token="${FORGE_ADMIN_TOKEN:-}"
  if [[ -z "$token" ]]; then
    error "FORGE_ADMIN_TOKEN is not set"
    exit 1
  fi

  options="$(jq_set '{}' '.issue_number' "$pr_number" '.token' "$token")"

  if already_prompted "$options"; then
    log "Blizz prompt already posted on PR #${pr_number}, skipping."
    return 0
  fi

  body="$(build_prompt)"
  forgejo_create_comment "$options" "$body" > /dev/null
  log "Posted Linear issue prompt on PR #${pr_number}"
}

function detect_pr_number() {
  [[ -z "${GITHUB_EVENT_PATH:-}" ]] && return
  [[ ! -f "$GITHUB_EVENT_PATH" ]] && return

  local event_json
  event_json="$(<"$GITHUB_EVENT_PATH")"
  jq_get "$event_json" '.pull_request.number' '.number' ''
}

function already_prompted() {
  local options="$1"
  local comments matching

  comments="$(forgejo_list_comments "$options")" || return 1
  matching="$(jq_filter "$comments" ".body | contains(\"$__prompt_refs__MARKER\")")"
  (( $(jq_len "$matching") > 0 ))
}

function build_prompt() {
  local team_key prefill_line hint detection

  team_key="$(manifest_get linear_team)" || team_key=""
  prefill_line="$(detect_branch_ref "$team_key")"

  hint=""
  [[ -n "$team_key" ]] && hint=" (e.g. \`ABC-###\`)"

  detection=""
  [[ -n "$prefill_line" ]] && detection=$'\n\n'"Detected from branch name: \`${prefill_line}\`"

  cat <<EOF
${__prompt_refs__MARKER}
**What Linear issue(s) does this PR address?**

Reply to this comment with issue identifiers${hint}.${detection}
EOF
}

function detect_branch_ref() {
  local team_key="$1"
  local branch upper_branch pattern

  branch="${GITHUB_HEAD_REF:-}"
  [[ -z "$branch" ]] && return
  [[ -z "$team_key" ]] && return

  upper_branch="$(echo "$branch" | tr '[:lower:]' '[:upper:]')"
  pattern="${team_key}-[0-9]+"
  if [[ "$upper_branch" =~ ($pattern) ]]; then
    echo "${BASH_REMATCH[1]}"
  fi
}

if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
  main "$@"
fi
