#!/usr/bin/env bash
# Parse Gitea webhook payload and decide whether to run the Cursor agent.
set -euo pipefail

if ! command -v jq >/dev/null 2>&1; then
  echo "Error: jq is required"
  exit 1
fi

EVENT_FILE="${GITHUB_EVENT_PATH:-}"
if [ -z "$EVENT_FILE" ] || [ ! -f "$EVENT_FILE" ]; then
  echo "Error: GITHUB_EVENT_PATH is not set or file is missing"
  exit 1
fi

OUTPUT_FILE="${GITHUB_OUTPUT:?GITHUB_OUTPUT is not set}"

COMMENT_BODY=$(jq -r '
  if .comment?.body? then .comment.body
  elif .review?.body? then .review.body
  else empty end
' "$EVENT_FILE")

if [ -z "$COMMENT_BODY" ]; then
  echo "No comment or review body in event payload — skipping."
  echo "run_cursor=false" >> "$OUTPUT_FILE"
  exit 0
fi

COMMENT_USER=$(jq -r '
  if .comment?.user?.login? then .comment.user.login
  elif .sender?.login? then .sender.login
  else "unknown" end
' "$EVENT_FILE")

printf '%s' "$COMMENT_BODY" > comment.txt

if echo "$COMMENT_USER" | grep -qiE '^cursor$'; then
  echo "Comment from cursor bot — skipping to avoid loops."
  echo "run_cursor=false" >> "$OUTPUT_FILE"
  exit 0
fi

if ! echo "$COMMENT_BODY" | grep -qiE '@cursor([^a-zA-Z0-9_]|$)'; then
  echo "No @cursor mention — skipping."
  echo "run_cursor=false" >> "$OUTPUT_FILE"
  exit 0
fi

jq \
  --arg event_name "${GITHUB_EVENT_NAME:-unknown}" \
  '
  {
    event_name: $event_name,
    comment: (
      if .comment then {
        body: .comment.body,
        id: .comment.id,
        user: (.comment.user.login // "unknown")
      }
      elif .review then {
        body: .review.body,
        id: .review.id,
        user: (.sender.login // "unknown")
      }
      else null end
    ),
    issue: {
      number: (
        .issue.number // .pull_request.number // .number // null
      ),
      title: (.issue.title // .pull_request.title // ""),
      body: (.issue.body // .pull_request.body // ""),
      state: (.issue.state // .pull_request.state // ""),
      user: (.issue.user.login // .pull_request.user.login // ""),
      html_url: (.issue.html_url // .pull_request.html_url // ""),
      is_pull_request: (
        (.pull_request != null)
        or (.issue.pull_request != null)
        or (.is_pull == true)
      )
    },
    repository: {
      name: .repository.name,
      owner: .repository.owner.login,
      full_name: .repository.full_name,
      html_url: .repository.html_url,
      default_branch: .repository.default_branch
    },
    sender: (.sender.login // "")
  }
  ' "$EVENT_FILE" > context.json

ISSUE_NUMBER=$(jq -r '.issue.number' context.json)

echo "run_cursor=true" >> "$OUTPUT_FILE"
echo "Triggered for ${COMMENT_USER} on issue/PR #${ISSUE_NUMBER} (event: ${GITHUB_EVENT_NAME:-unknown})"
