#!/bin/bash
# Post a comment on a GitHub pull request using gh CLI.
#
# Usage:
#   pr-comment.sh <pr-number> --body "<markdown body>"
#   pr-comment.sh <pr-number> --body-file <path-to-markdown-file>
#
# Use --body-file for any body longer than a few lines — passes the file
# directly to gh, avoiding shell quoting issues with multi-line markdown.

set -e

PR_NUMBER="$1"
shift || true

if [ -z "$PR_NUMBER" ] || [ -z "$1" ]; then
    echo "Error: Missing required arguments" >&2
    echo "Usage: $0 <pr-number> --body \"<text>\"" >&2
    echo "       $0 <pr-number> --body-file <path>" >&2
    exit 1
fi

if ! command -v gh &> /dev/null; then
    echo "Error: GitHub CLI (gh) is not installed" >&2
    echo "Install: https://cli.github.com/" >&2
    exit 1
fi

case "$1" in
    --body)
        BODY="$2"
        if [ -z "$BODY" ]; then
            echo "Error: --body requires a non-empty value" >&2
            exit 1
        fi
        gh pr comment "$PR_NUMBER" --body "$BODY"
        ;;
    --body-file)
        BODY_FILE="$2"
        if [ -z "$BODY_FILE" ] || [ ! -f "$BODY_FILE" ]; then
            echo "Error: --body-file requires a path to an existing file (got: ${BODY_FILE:-<empty>})" >&2
            exit 1
        fi
        gh pr comment "$PR_NUMBER" --body-file "$BODY_FILE"
        ;;
    *)
        echo "Error: expected --body or --body-file, got: $1" >&2
        exit 1
        ;;
esac
