#!/usr/bin/env bash
# Post a stage completion comment to the current PR (D-055).
#
# Usage: post_stage_comment.sh <stage_name> <status> <details_json>
#
# Uses GITHUB_TOKEN + the GitHub API via curl. No-op when not in a PR context
# (push to main) or when no token is available.
#
# The comment format:
#   ### ACDL Stage: <stage_name> — <status>
#   <details as a table or bullet list from details_json>
set -euo pipefail

STAGE="${1:-unknown}"
STATUS="${2:-unknown}"
DETAILS="${3:-{}}"

# Extract PR number from GITHUB_REF
REF="${GITHUB_REF:-}"
PR_NUMBER=""
if [[ "$REF" == refs/pull/* ]]; then
  PR_NUMBER=$(echo "$REF" | sed -n 's|refs/pull/\([0-9]*\)/.*|\1|p')
fi

TOKEN="${GITHUB_TOKEN:-${GH_TOKEN:-}}"
REPO="${GITHUB_REPOSITORY:-}"

# No-op if not in a PR context or no token
if [ -z "$PR_NUMBER" ] || [ -z "$TOKEN" ] || [ -z "$REPO" ]; then
  exit 0
fi

# Build the comment body
BODY=$(python3 -c "
import json, sys
stage = '''$STAGE'''
status = '''$STATUS'''
details = json.loads('''$DETAILS''')
lines = [f'### ACDL Stage: {stage} — {status}', '']
if details:
    lines.append('| Metric | Value |')
    lines.append('|--------|-------|')
    for k, v in details.items():
        lines.append(f'| {k} | {v} |')
    lines.append('')
lines.append('> _Auto-posted by the ACDL deploy pipeline (D-055)._')
print('\n'.join(lines))
")

# Post via the GitHub API
curl -sS -X POST \
  -H "Authorization: token $TOKEN" \
  -H "Accept: application/vnd.github+json" \
  "https://api.github.com/repos/$REPO/issues/$PR_NUMBER/comments" \
  -d "$(python3 -c "import json,sys; print(json.dumps({'body': sys.stdin.read()}))" <<< "$BODY")" \
  >/dev/null 2>&1 || true