#!/usr/bin/env bash
# pr-comment-example.sh
#
# yagra explain の出力を GitHub PR コメントに投稿するサンプルスクリプト。
# GitHub Actions の `actions/github-script` の代わりに gh CLI を使う場合の例です。
#
# 使い方:
#   bash scripts/pr-comment-example.sh <workflow_file> <pr_number>
#
# 必要な環境変数:
#   GITHUB_TOKEN  - GitHub Personal Access Token（または GITHUB_TOKEN）
#   GITHUB_REPO   - "owner/repo" 形式（例: "shogo-hs/Yagra"）
#
# 例:
#   GITHUB_TOKEN=ghp_xxx GITHUB_REPO=shogo-hs/Yagra \
#     bash scripts/pr-comment-example.sh workflows/my-workflow.yaml 42

set -euo pipefail

WORKFLOW_FILE="${1:?'Usage: $0 <workflow_file> <pr_number>'}"
PR_NUMBER="${2:?'Usage: $0 <workflow_file> <pr_number>'}"

GITHUB_TOKEN="${GITHUB_TOKEN:?'GITHUB_TOKEN is required'}"
GITHUB_REPO="${GITHUB_REPO:?'GITHUB_REPO is required (format: owner/repo)'}"

# --- validate ---
echo "Validating: $WORKFLOW_FILE"
VALIDATE_OUTPUT=$(yagra validate --workflow "$WORKFLOW_FILE" --format json 2>&1) || true
VALIDATE_EXIT=$?

if [ "$VALIDATE_EXIT" -eq 0 ]; then
  VALIDATE_ICON="✅"
  VALIDATE_STATUS="Valid"
else
  VALIDATE_ICON="❌"
  VALIDATE_STATUS="Invalid"
fi

# --- explain ---
echo "Explaining: $WORKFLOW_FILE"
EXPLAIN_OUTPUT=$(yagra explain --workflow "$WORKFLOW_FILE" --format text 2>&1) || true

# --- コメント本文を組み立て ---
COMMENT_BODY=$(cat <<EOF
## 🔍 Yagra Workflow Report: \`$WORKFLOW_FILE\`

### ${VALIDATE_ICON} Validation: ${VALIDATE_STATUS}

\`\`\`json
${VALIDATE_OUTPUT}
\`\`\`

### 📊 Workflow Analysis

\`\`\`
${EXPLAIN_OUTPUT}
\`\`\`

_Generated by [yagra](https://github.com/shogo-hs/Yagra)_
EOF
)

# --- PR コメントを投稿 ---
echo "Posting comment to PR #${PR_NUMBER}..."

gh api \
  --method POST \
  -H "Authorization: Bearer $GITHUB_TOKEN" \
  -H "Accept: application/vnd.github+json" \
  "/repos/${GITHUB_REPO}/issues/${PR_NUMBER}/comments" \
  -f "body=${COMMENT_BODY}"

echo "Done. Comment posted to PR #${PR_NUMBER}."
