#!/usr/bin/env bash
# Wait for pipeline to complete and create GitLab release
# Usage: ./scripts/create-release-when-ready <tag> <pipeline_id>
set -euo pipefail

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}ℹ${NC} $*"; }
log_success() { echo -e "${GREEN}✓${NC} $*"; }
log_warn() { echo -e "${YELLOW}⚠${NC} $*"; }
log_error() { echo -e "${RED}✗${NC} $*"; }

TAG="${1:-v6.0.0-rc.3}"
PIPELINE_ID="${2:-8880}"

log_info "Waiting for pipeline #$PIPELINE_ID to complete..."
log_info "Tag: $TAG"
log_info "Pipeline: https://gitlab.satware.com/satware/satag-amicron-entity-bundle/-/pipelines/$PIPELINE_ID"

# Wait for pipeline completion
MAX_WAIT=600  # 10 minutes
ELAPSED=0
CHECK_INTERVAL=15

while [ $ELAPSED -lt $MAX_WAIT ]; do
    STATUS=$(glab api /projects/:id/pipelines/$PIPELINE_ID | jq -r '.status')
    
    if [ "$STATUS" = "success" ]; then
        log_success "Pipeline completed successfully!"
        break
    elif [ "$STATUS" = "failed" ]; then
        log_error "Pipeline failed!"
        log_error "Fix issues and re-run: ./scripts/create-release-when-ready $TAG"
        exit 1
    fi
    
    echo -ne "\r⏳ Waiting... ${ELAPSED}s elapsed (status: $STATUS)"
    sleep $CHECK_INTERVAL
    ((ELAPSED+=CHECK_INTERVAL))
done

if [ $ELAPSED -ge $MAX_WAIT ]; then
    log_warn "Timeout waiting for pipeline"
    log_info "Check manually: glab ci view"
    exit 1
fi

echo ""
log_info "Creating GitLab release for $TAG..."

# Extract tag message for release notes
TAG_MESSAGE=$(git tag -l --format='%(contents)' "$TAG")

# Create release via GitLab API
glab api /projects/:id/releases --method POST \
    -f tag_name="$TAG" \
    -f name="$TAG" \
    -f description="$TAG_MESSAGE" \
    > /dev/null

log_success "Release created: https://gitlab.satware.com/satware/satag-amicron-entity-bundle/-/releases/$TAG"
log_info "View all releases: glab release list"

echo ""
log_success "✨ Release $TAG is ready!"