#!/bin/bash
set -e

# Convert JSON string to JSON object for jq
if ! echo "$WORKFLOW_INPUTS" | jq empty; then
  echo "Invalid JSON in workflow_inputs"
  exit 1
fi

# Get the workflow ID
WORKFLOW_ID=$(curl -s \
  -H "Accept: application/vnd.github+json" \
  -H "Authorization: Bearer $TOKEN" \
  "https://api.github.com/repos/$OWNER/$REPO/actions/workflows" \
  | jq '.workflows[] | select(.name == "'"$WORKFLOW_NAME"'") | .id')

if [ -z "$WORKFLOW_ID" ] || [ "$WORKFLOW_ID" == "null" ]; then
  echo "Workflow '$WORKFLOW_NAME' not found in $OWNER/$REPO"
  exit 1
fi

# Prepare the data for dispatch
DATA=$(jq -n \
  --arg ref "$REF" \
  --argjson inputs "$WORKFLOW_INPUTS" \
  '{ref: $ref, inputs: $inputs}')

# Trigger the workflow
curl -s -X POST \
  -H "Accept: application/vnd.github+json" \
  -H "Authorization: Bearer $TOKEN" \
  "https://api.github.com/repos/$OWNER/$REPO/actions/workflows/$WORKFLOW_ID/dispatches" \
  -d "$DATA"

# Wait for a few seconds to ensure the workflow run is initiated
sleep 10

# Initialize variables
workflow_run_id=""
attempts=0

# Wait for the workflow run to start and retrieve the run ID using branch name
while [[ -z "$workflow_run_id" && $attempts -lt $MAX_ATTEMPTS ]]; do
  workflow_run_id=$(curl -s \
    -H "Accept: application/vnd.github+json" \
    -H "Authorization: Bearer $TOKEN" \
    "https://api.github.com/repos/$OWNER/$REPO/actions/runs?event=workflow_dispatch&branch=$REF" \
    | jq -r '.workflow_runs[] | select(.head_branch=="'"$REF"'") | .id' | head -n 1)
  
  if [[ -z "$workflow_run_id" ]]; then
    echo "Waiting for workflow run to start..."
    sleep "$POLL_INTERVAL"
    ((attempts++))
  fi
done

# Construct the workflow run URL
if [[ -n "$workflow_run_id" ]]; then
  workflow_url="https://github.com/$OWNER/$REPO/actions/runs/$workflow_run_id"
  echo "workflow_run_id=$workflow_run_id" >> "$GITHUB_OUTPUT"
  echo "workflow_url=$workflow_url" >> "$GITHUB_OUTPUT"
  echo "Workflow run started: $workflow_url"
else
  echo "Failed to retrieve workflow run ID after $MAX_ATTEMPTS attempts."
  exit 1
fi
