#!/bin/bash
set -e

WORKFLOW_URL="https://github.com/$OWNER/$REPO/actions/runs/$RUN_ID"
echo "Triggered workflow URL: $WORKFLOW_URL"
echo "workflow_url=$WORKFLOW_URL" >> "$GITHUB_OUTPUT"

sleep 10
run_found=false
attempts=0

while true; do
  # Fetch the workflow run details and capture the HTTP status code
  http_response=$(curl -s -o response.json -w "%{http_code}" \
    -H "Accept: application/vnd.github+json" \
    -H "Authorization: Bearer $TOKEN" \
    "https://api.github.com/repos/$OWNER/$REPO/actions/runs/$RUN_ID")

  if [ "$http_response" -eq 200 ]; then
    run_found=true
    status=$(jq -r '.status' response.json)
    conclusion=$(jq -r '.conclusion' response.json)
    # echo "Workflow status: $status, conclusion: $conclusion"

    if [ "$status" == "completed" ]; then
      if [ "$conclusion" == "success" ]; then
        echo "🎉 Workflow completed successfully."
        echo "conclusion=success" >> "$GITHUB_OUTPUT"
        exit 0
      elif [ "$conclusion" == "cancelled" ]; then
        echo "🚫 Workflow was cancelled."
        echo "conclusion=cancelled" >> "$GITHUB_OUTPUT"
        exit 1
      else
        echo "⚠️ Workflow completed with conclusion: $conclusion."
        echo "conclusion=$conclusion" >> "$GITHUB_OUTPUT"
        exit 1
      fi
    elif [ "$status" == "in_progress" ] || [ "$status" == "queued" ]; then
      echo "⏳ Workflow is in progress. Current status: $status."
      sleep "$POLL_INTERVAL"
    else
      echo "❗ Unexpected workflow status: $status. Exiting."
      exit 1
    fi
  elif [ "$http_response" -eq 404 ]; then
    if [ "$run_found" = true ]; then
      echo "🚫 Workflow run is no longer accessible. It might have been cancelled."
      exit 1
    else
      echo "🔄 Workflow run not found yet. Waiting for it to start..."
      sleep 10
      attempts=$((attempts+1))
      if [ "$attempts" -ge "$MAX_ATTEMPTS" ]; then
        echo "❗ Maximum attempts reached while waiting for the workflow to start. Exiting."
        exit 1
      fi
    fi
  else
    echo "❗ Error fetching workflow run: HTTP status $http_response."
    echo "Debug: Response body:"
    cat response.json
    exit 1
  fi
done
