#!/bin/bash
set -e

OWNER=$(echo $GITHUB_REPOSITORY | cut -d'/' -f1)
REPO=$(echo $GITHUB_REPOSITORY | cut -d'/' -f2)
BRANCH=$GITHUB_REF_NAME
WORKFLOW_NAME=$GITHUB_WORKFLOW

echo "Owner: $OWNER"
echo "Repo: $REPO"
echo "Branch: $BRANCH"
echo "Workflow Name: $WORKFLOW_NAME"

# Function to check if a commit has a successful workflow run
is_commit_green() {
    local commit_sha=$1
    local runs_url="https://api.github.com/repos/$OWNER/$REPO/actions/runs?head_sha=$commit_sha"
    local response=$(curl -s -H "Authorization: token $GITHUB_TOKEN" -H "Accept: application/vnd.github.v3+json" "$runs_url")
    
    # Check if the response is valid JSON
    if ! echo "$response" | jq empty > /dev/null 2>&1; then
        echo "Error: Invalid JSON response from API"
        echo "Response: $response"
        return 1
    fi

    local total_count=$(echo $response | jq -r '.total_count')
    
    # Check if total_count is a number
    if ! [[ "$total_count" =~ ^[0-9]+$ ]] ; then
        echo "Error: Invalid total_count: $total_count"
        echo "Response: $response"
        return 1
    fi

    if [ "$total_count" -eq 0 ]; then
        echo "No workflow runs found for this commit"
        return 1
    fi

    # Check for successful runs of the specific workflow
    local success_count=$(echo $response | jq -r --arg name "$WORKFLOW_NAME" '.workflow_runs[] | select(.conclusion == "success" and .name == $name) | .id' | wc -l)
    
    if [ "$success_count" -gt 0 ]; then
        return 0  # Green
    else
        return 1  # Not green
    fi
}

# Get all commits in reverse order, excluding the most recent one
all_commits=$(git rev-list HEAD | tail -n +2)

# Loop through commits and check their status
echo "Checking commits for green status..."
for commit in $all_commits; do
    echo "Checking commit: $commit"
    if is_commit_green $commit; then
        echo "Found green commit: $commit"
        echo "last_green_commit=$commit" >> "$GITHUB_OUTPUT"
        exit 0
    fi
done

echo "No green commit found"
exit 1