#!/bin/bash

# Exit on any error
set -e

# Function to display usage information
usage() {
    echo "Usage: $0 <version> [options]"
    echo "  version    : Version to tag (e.g., v1.2.3, v1.2.3-alpha, v2.0.0-beta)"
    echo ""
    echo "Options:"
    echo "  --services <service1,service2,...> : Specific services to tag (default: all EveAI services)"
    echo "  --dry-run                          : Show what would be done without executing"
    echo "  --force                            : Overwrite existing version tags"
    echo ""
    echo "Examples:"
    echo "  $0 v1.2.3-alpha"
    echo "  $0 v2.0.0 --services eveai_api,eveai_workers"
    echo "  $0 v1.0.0-beta --dry-run"
}

# Check if version is provided
if [ $# -eq 0 ]; then
    echo "❌ Error: Version is required"
    usage
    exit 1
fi

VERSION=$1
shift

# Default values
SERVICES=""
DRY_RUN=false
FORCE=false

# Parse options
while [[ $# -gt 0 ]]; do
    case $1 in
        --services)
            SERVICES="$2"
            shift 2
            ;;
        --dry-run)
            DRY_RUN=true
            shift
            ;;
        --force)
            FORCE=true
            shift
            ;;
        -*)
            echo "❌ Unknown option: $1"
            usage
            exit 1
            ;;
        *)
            echo "❌ Unexpected argument: $1"
            usage
            exit 1
            ;;
    esac
done

# Validate version format (flexible semantic versioning)
if [[ ! "$VERSION" =~ ^v?[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9\-]+)?$ ]]; then
    echo "❌ Error: Invalid version format. Expected format: v1.2.3 or v1.2.3-alpha"
    echo "   Examples: v1.0.0, v2.1.3-beta, v1.0.0-rc1"
    exit 1
fi

# Ensure version starts with 'v'
if [[ ! "$VERSION" =~ ^v ]]; then
    VERSION="v$VERSION"
fi

# Local registry configuration
REGISTRY="registry.ask-eve-ai-local.com"
ACCOUNT="josakola"

# Check if podman is available
if ! command -v podman &> /dev/null; then
    echo "❌ Error: podman not found"
    exit 1
fi

# Check if yq is available
if ! command -v yq &> /dev/null; then
    echo "❌ Error: yq not found (required for parsing compose file)"
    exit 1
fi

# Check if compose file exists
COMPOSE_FILE="compose_dev.yaml"
if [[ ! -f "$COMPOSE_FILE" ]]; then
    echo "❌ Error: Compose file '$COMPOSE_FILE' not found"
    exit 1
fi

echo "🏷️  EveAI Registry Version Tagging Script"
echo "📦 Version: $VERSION"
echo "🏪 Registry: $REGISTRY"
echo "👤 Account: $ACCOUNT"

# Get services to process
if [[ -n "$SERVICES" ]]; then
    # Convert comma-separated list to array
    IFS=',' read -ra SERVICE_ARRAY <<< "$SERVICES"
else
    # Get all EveAI services (excluding nginx as per requirements)
    SERVICE_ARRAY=()
    while IFS= read -r line; do
        SERVICE_ARRAY+=("$line")
    done < <(yq e '.services | keys | .[]' "$COMPOSE_FILE" | grep -E '^eveai_')
fi

echo "🔍 Services to process: ${SERVICE_ARRAY[*]}"

# Function to check if image exists in registry
check_image_exists() {
    local image_name="$1"
    if podman image exists "$image_name" 2>/dev/null; then
        return 0
    else
        return 1
    fi
}

# Function to check if version tag already exists
check_version_exists() {
    local service="$1"
    local version_tag="$REGISTRY/$ACCOUNT/$service:$VERSION"
    
    # Try to inspect the image in the registry
    if podman image exists "$version_tag" 2>/dev/null; then
        return 0
    else
        return 1
    fi
}

# Process each service
PROCESSED_SERVICES=()
FAILED_SERVICES=()

for SERVICE in "${SERVICE_ARRAY[@]}"; do
    echo ""
    echo "🔄 Processing service: $SERVICE"
    
    # Check if service exists in compose file
    if ! yq e ".services.$SERVICE" "$COMPOSE_FILE" | grep -q "image:"; then
        echo "⚠️  Warning: Service '$SERVICE' not found in $COMPOSE_FILE, skipping"
        continue
    fi
    
    # Construct image names
    LATEST_IMAGE="$REGISTRY/$ACCOUNT/$SERVICE:latest"
    VERSION_IMAGE="$REGISTRY/$ACCOUNT/$SERVICE:$VERSION"
    
    echo "   📥 Source: $LATEST_IMAGE"
    echo "   🏷️  Target: $VERSION_IMAGE"
    
    # Check if version already exists
    if check_version_exists "$SERVICE" && [[ "$FORCE" != true ]]; then
        echo "   ⚠️  Version $VERSION already exists for $SERVICE"
        echo "   💡 Use --force to overwrite existing tags"
        continue
    fi
    
    if [[ "$DRY_RUN" == true ]]; then
        echo "   🔍 [DRY RUN] Would tag $LATEST_IMAGE as $VERSION_IMAGE"
        PROCESSED_SERVICES+=("$SERVICE")
        continue
    fi
    
    # Check if latest image exists
    if ! check_image_exists "$LATEST_IMAGE"; then
        echo "   ❌ Latest image not found: $LATEST_IMAGE"
        echo "   💡 Run build_and_push_eveai.sh first to create latest images"
        FAILED_SERVICES+=("$SERVICE")
        continue
    fi
    
    # Pull latest image
    echo "   📥 Pulling latest image..."
    if ! podman pull "$LATEST_IMAGE"; then
        echo "   ❌ Failed to pull $LATEST_IMAGE"
        FAILED_SERVICES+=("$SERVICE")
        continue
    fi
    
    # Tag with version
    echo "   🏷️  Tagging with version $VERSION..."
    if ! podman tag "$LATEST_IMAGE" "$VERSION_IMAGE"; then
        echo "   ❌ Failed to tag $LATEST_IMAGE as $VERSION_IMAGE"
        FAILED_SERVICES+=("$SERVICE")
        continue
    fi
    
    # Push version tag to registry
    echo "   📤 Pushing version tag to registry..."
    if ! podman push "$VERSION_IMAGE"; then
        echo "   ❌ Failed to push $VERSION_IMAGE"
        FAILED_SERVICES+=("$SERVICE")
        continue
    fi
    
    echo "   ✅ Successfully tagged $SERVICE with version $VERSION"
    PROCESSED_SERVICES+=("$SERVICE")
done

# Summary
echo ""
echo "📊 Summary:"
echo "✅ Successfully processed: ${#PROCESSED_SERVICES[@]} services"
if [[ ${#PROCESSED_SERVICES[@]} -gt 0 ]]; then
    printf "   - %s\n" "${PROCESSED_SERVICES[@]}"
fi

if [[ ${#FAILED_SERVICES[@]} -gt 0 ]]; then
    echo "❌ Failed: ${#FAILED_SERVICES[@]} services"
    printf "   - %s\n" "${FAILED_SERVICES[@]}"
fi

if [[ "$DRY_RUN" == true ]]; then
    echo "🔍 This was a dry run - no actual changes were made"
fi

echo ""
if [[ ${#FAILED_SERVICES[@]} -eq 0 ]]; then
    echo "🎉 All services successfully tagged with version $VERSION!"
    echo "📦 Images are available in registry: $REGISTRY/$ACCOUNT/[service]:$VERSION"
else
    echo "⚠️  Some services failed to process. Check the errors above."
    exit 1
fi

echo "🕐 Finished at $(date +"%d/%m/%Y %H:%M:%S")"