#!/usr/bin/env zsh

# Script to find PRs not mentioned in the changelog
#
# Disclaimer: This script was auto-generated by Claude Code.
#
# Usage: ./cicd_utils/find-unmentioned-prs.sh
#
# Note: Take a look at the `all_prs=($(gh pr list ...))` line to see all the filters used to fetch PRs.
#
# Requirements:
# * GitHub CLI (gh) must be installed and authenticated.
# * jq must be installed for JSON parsing.
# * The changelog file must exist at ./docs/reference/changelog.md
# * The script assumes the main branch is named 'main'
# * PRs are referenced in the changelog using the pattern {gh-pr}`PR-NUMBER`
# * The script should be run from the root of the repository

set -e

CHANGELOG_FILE="./docs/reference/changelog.md"

# Check if changelog file exists
if [[ ! -f "$CHANGELOG_FILE" ]]; then
    echo "Error: Changelog file not found at $CHANGELOG_FILE"
    exit 1
fi

# Check if gh CLI is available
if ! command -v gh &> /dev/null; then
    echo "Error: GitHub CLI (gh) is not installed"
    exit 1
fi

echo "🔍 Finding PRs not mentioned in changelog..."
echo

# Get all PR numbers from GitHub (both open and closed)
echo "📥 Fetching all PRs from GitHub..."
all_prs=($(gh pr list --state merged --base main --label 'skip news' --search 'merged:>2025-09-01' --limit 100 --json number --jq '.[].number'))
if [[ ${#all_prs[@]} -eq 0 ]]; then
    echo "No PRs found in this repository."
    exit 0
fi

echo "Found ${#all_prs[@]} total PRs"

# Extract PR numbers mentioned in changelog using the pattern {gh-pr}`PR-NUMBER`
echo "📖 Parsing changelog for mentioned PRs..."
mentioned_prs=($(grep -o '{gh-pr}`[0-9]\+`' "$CHANGELOG_FILE" | sed 's/{gh-pr}`\([0-9]\+\)`/\1/' | sort -n | uniq))

echo "Found ${#mentioned_prs[@]} PRs mentioned in changelog"
echo

# Find PRs not mentioned in changelog
unmentioned_prs=()

for pr in "${all_prs[@]}"; do
    if [[ ! " ${mentioned_prs[*]} " =~ " $pr " ]]; then
        unmentioned_prs+=($pr)
    fi
done

# Display results
if [[ ${#unmentioned_prs[@]} -eq 0 ]]; then
    echo "✅ All PRs are mentioned in the changelog!"
else
    echo "📋 PRs not mentioned in changelog (${#unmentioned_prs[@]} total):"
    echo

    for pr in "${unmentioned_prs[@]}"; do
        # Get PR title and URL for better readability
        pr_info=$(gh pr view "$pr" --json title,url --jq '{title: .title, url: .url}')
        pr_title=$(echo "$pr_info" | jq -r '.title')
        pr_url=$(echo "$pr_info" | jq -r '.url')

        echo "  #$pr: $pr_title"
        echo "       $pr_url"
        echo
    done
fi
