#!/bin/bash

# Check for required tools
for tool in jq curl; do
    if ! command -v $tool &>/dev/null; then
        echo "Error: Required tool '$tool' is not installed." >&2
        exit 1
    fi
done

if [[ -z "$GITHUB_TOKEN" ]]; then
    echo "Error: GITHUB_TOKEN is not set in your environment." >&2
    exit 1
fi

# Get authenticated username
AUTH_USER=$(curl -s -H "Authorization: token $GITHUB_TOKEN" https://api.github.com/user | jq -r '.login')
if [[ -z "$AUTH_USER" || "$AUTH_USER" == "null" ]]; then
    echo "Error: Could not determine authenticated user. Check your GITHUB_TOKEN." >&2
    exit 1
fi

read -p "Enter GitHub organization/user (default: $AUTH_USER): " ORG
if [[ -z "$ORG" ]]; then
    ORG="$AUTH_USER"
fi

read -p "Enter PR author username (default: $AUTH_USER): " PR_AUTHOR
if [[ -z "$PR_AUTHOR" ]]; then
    PR_AUTHOR="$AUTH_USER"
fi

REPOS_JSON=$(curl -s -H "Authorization: token $GITHUB_TOKEN" "https://api.github.com/users/$ORG/repos?per_page=100")
if ! echo "$REPOS_JSON" | jq -e 'type == "array"' >/dev/null; then
    REPOS_JSON=$(curl -s -H "Authorization: token $GITHUB_TOKEN" "https://api.github.com/orgs/$ORG/repos?per_page=100")
    if ! echo "$REPOS_JSON" | jq -e 'type == "array"' >/dev/null; then
        echo "GitHub API error:" >&2
        echo "$REPOS_JSON" | jq .
        echo "No repositories found for $ORG."
        exit 1
    fi
fi
REPOS=$(echo "$REPOS_JSON" | jq -r '.[].name')

if [[ -z "$REPOS" ]]; then
    echo "No repositories found for $ORG."
    exit 0
fi

found_prs=0

for REPO in $REPOS; do
    PRS=$(curl -s -H "Authorization: token $GITHUB_TOKEN" \
        "https://api.github.com/repos/$ORG/$REPO/pulls?state=all&per_page=100" | \
        jq -c --arg user "$PR_AUTHOR" '.[] | select(.user.login == $user)')
    if [[ -z "$PRS" ]]; then
        continue
    fi
    echo "$REPO:"
    echo "$PRS" | while read -r pr; do
        NUMBER=$(echo "$pr" | jq -r '.number')
        TITLE=$(echo "$pr" | jq -r '.title')
        STATE=$(echo "$pr" | jq -r '.state')
        DRAFT=$(echo "$pr" | jq -r '.draft')
        URL=$(echo "$pr" | jq -r '.html_url')
        MERGED=$(curl -s -H "Authorization: token $GITHUB_TOKEN" \
            "https://api.github.com/repos/$ORG/$REPO/pulls/$NUMBER/merge" | jq -r '.merged // empty')
        if [[ "$DRAFT" == "true" ]]; then
            STATUS="draft"
        elif [[ "$STATE" == "open" ]]; then
            STATUS="open"
        elif [[ "$STATE" == "closed" && "$MERGED" == "true" ]]; then
            STATUS="merged"
        elif [[ "$STATE" == "closed" ]]; then
            STATUS="closed"
        else
            STATUS="other"
        fi
        echo "  #$NUMBER $TITLE"
        echo "    Status: $STATUS"
        echo "    $URL"
        found_prs=1
    done
    echo
 done

if [[ $found_prs -eq 0 ]]; then
    echo "No pull requests found for user $PR_AUTHOR in $ORG."
fi 