#!/bin/bash
set -e

# wait-for-upstream.sh
# Usage: ./wait-for-upstream.sh <org/repo> <version_tag> [poll_interval_sec]

REPO=$1
TAG=$2
INTERVAL=${3:-30}
MAX_RETRIES=40 # ~20 minutes default

if [[ -z "$REPO" || -z "$TAG" ]]; then
  echo "❌ Error: REPO and TAG are required."
  echo "Usage: $0 <org/repo> <version_tag>"
  exit 1
fi

if [[ -z "$GITEA_TOKEN" ]]; then
  echo "❌ Error: GITEA_TOKEN is not set."
  exit 1
fi

GITEA_API="https://git.infra.mintel.me/api/v1"

echo "🔎 Searching for upstream release $TAG in $REPO..."

# 1. Get the SHA of the tag to be more precise
TAG_INFO=$(curl -s -H "Authorization: token $GITEA_TOKEN" "$GITEA_API/repos/$REPO/tags/$TAG")
TARGET_SHA=$(echo "$TAG_INFO" | jq -r '.commit.sha // empty')

if [[ -z "$TARGET_SHA" || "$TARGET_SHA" == "null" ]]; then
  echo "⚠️ Warning: Tag $TAG not found yet. Upstream might be lagging."
  echo "   Waiting 15s for tag to appear..."
  sleep 15
  TAG_INFO=$(curl -s -H "Authorization: token $GITEA_TOKEN" "$GITEA_API/repos/$REPO/tags/$TAG")
  TARGET_SHA=$(echo "$TAG_INFO" | jq -r '.commit.sha // empty')
  
  if [[ -z "$TARGET_SHA" || "$TARGET_SHA" == "null" ]]; then
    echo "❌ Error: Tag $TAG does not exist in $REPO."
    exit 1
  fi
fi

echo "✅ Target SHA for $TAG is $TARGET_SHA"

# 2. Find the run for the specific SHA
# We list recent runs and filter by head_sha
RUN_QUERY=$(curl -s -H "Authorization: token $GITEA_TOKEN" "$GITEA_API/repos/$REPO/actions/runs?limit=30")
RUN_ID=$(echo "$RUN_QUERY" | jq -r ".workflow_runs[] | select(.head_sha == \"$TARGET_SHA\") | .id" | head -n 1)

if [[ -z "$RUN_ID" || "$RUN_ID" == "null" ]]; then
  echo "ℹ️ No recent action run found for SHA $TARGET_SHA yet."
  echo "   Checking if we should wait or if it was already successful..."
  
  # Fallback: wait a bit more for new tags
  echo "⏳ waiting for run to appear..."
  sleep 20
  RUN_QUERY=$(curl -s -H "Authorization: token $GITEA_TOKEN" "$GITEA_API/repos/$REPO/actions/runs?limit=30")
  RUN_ID=$(echo "$RUN_QUERY" | jq -r ".workflow_runs[] | select(.head_sha == \"$TARGET_SHA\") | .id" | head -n 1)
  
  if [[ -z "$RUN_ID" || "$RUN_ID" == "null" ]]; then
     echo "✅ No run found but Tag exists. Assuming manual release or already completed. Proceeding."
     exit 0
  fi
fi

echo "⏳ Waiting for upstream run $RUN_ID status..."

RETRY_COUNT=0
while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
  STATUS_QUERY=$(curl -s -H "Authorization: token $GITEA_TOKEN" "$GITEA_API/repos/$REPO/actions/runs/$RUN_ID")
  STATUS=$(echo "$STATUS_QUERY" | jq -r '.status')
  CONCLUSION=$(echo "$STATUS_QUERY" | jq -r '.conclusion')

  echo "   - Current Status: $STATUS (Conclusion: $CONCLUSION)"

  if [[ "$STATUS" == "success" || "$CONCLUSION" == "success" ]]; then
    echo "✅ Upstream release $TAG is READY."
    exit 0
  fi

  if [[ "$STATUS" == "failure" || "$CONCLUSION" == "failure" || "$CONCLUSION" == "cancelled" ]]; then
    echo "❌ Error: Upstream release $TAG FAILED or was CANCELLED."
    exit 1
  fi

  echo "   - Still working... waiting $INTERVAL seconds (Attempt $((RETRY_COUNT+1))/$MAX_RETRIES)"
  sleep $INTERVAL
  RETRY_COUNT=$((RETRY_COUNT+1))
done

echo "❌ Error: Timeout waiting for upstream release $TAG."
exit 1
