#!/bin/bash
# List GitHub Actions workflow runs using gh CLI

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib.sh
source "$SCRIPT_DIR/lib.sh"

# Arguments
WORKFLOW="$1"
LIMIT="${2:-10}"
STATUS="$3"

# Check if gh is installed
if ! command -v gh &> /dev/null; then
    echo "Error: GitHub CLI (gh) is not installed" >&2
    exit 1
fi

# gh is piped into jq below, and a pipeline reports jq's exit status, so a
# failed gh call would leave this script printing nothing and exiting 0. The
# guard catches the common cause, being run outside the repository. Any other
# gh failure is still swallowed by that pipe; see the note in lib.sh.
require_repo_context

# Build command
CMD="gh run list --limit $LIMIT --json databaseId,name,workflowName,headBranch,event,status,conclusion,createdAt,url"

# Restrict to one workflow when given: a filename like jira-transition.yml,
# or the workflow's display name.
if [ -n "$WORKFLOW" ]; then
    CMD="$CMD --workflow \"$WORKFLOW\""
fi

# Narrow to a single conclusion or status, e.g. failure, success, in_progress
if [ -n "$STATUS" ]; then
    CMD="$CMD --status $STATUS"
fi

# Execute and format
eval "$CMD" | jq '.'
