#!/bin/bash

# Script to release tempest lock files and kill any hanging pytest/tempest processes
# Usage: ./scripts/release_tempest_locks.sh

set -e

echo "🔓 Tempest Lock Release Script"
echo "=============================="

# Function to check and kill pytest/tempest processes
cleanup_processes() {
    echo "📋 Checking for running pytest/tempest processes..."

    # Find pytest/tempest processes (excluding this script and grep itself)
    PROCESSES=$(ps aux | grep -E "(pytest|tempest)" | grep -v grep | grep -v "release_tempest_locks" || true)

    if [ -n "$PROCESSES" ]; then
        echo "🚫 Found running pytest/tempest processes:"
        echo "$PROCESSES"
        echo ""

        # Extract PIDs and kill them
        PIDS=$(echo "$PROCESSES" | awk '{print $2}')
        for PID in $PIDS; do
            echo "⚡ Killing process $PID..."
            kill -9 "$PID" 2>/dev/null || echo "   ⚠️  Process $PID already terminated"
        done
        echo ""
    else
        echo "✅ No pytest/tempest processes found running"
    fi
}

# Function to remove tempest lock directory
cleanup_locks() {
    echo "🗂️  Checking for tempest_lock directory..."

    if [ -d "tempest_lock" ]; then
        echo "🔒 Found tempest_lock directory, removing..."
        rm -rf tempest_lock/
        echo "✅ tempest_lock directory removed successfully"
    else
        echo "✅ No tempest_lock directory found (already clean)"
    fi
}

# Function to verify cleanup
verify_cleanup() {
    echo ""
    echo "🔍 Verification:"
    echo "================"

    # Check processes again
    REMAINING_PROCESSES=$(ps aux | grep -E "(pytest|tempest)" | grep -v grep | grep -v "release_tempest_locks" || true)
    if [ -n "$REMAINING_PROCESSES" ]; then
        echo "⚠️  Warning: Some pytest/tempest processes are still running:"
        echo "$REMAINING_PROCESSES"
    else
        echo "✅ No pytest/tempest processes running"
    fi

    # Check lock directory
    if [ -d "tempest_lock" ]; then
        echo "⚠️  Warning: tempest_lock directory still exists"
        ls -la tempest_lock/
    else
        echo "✅ tempest_lock directory successfully removed"
    fi
}

# Main execution
main() {
    # Change to script directory's parent (project root)
    cd "$(dirname "$0")/.."

    echo "📂 Working in: $(pwd)"
    echo ""

    cleanup_processes
    cleanup_locks
    verify_cleanup

    echo ""
    echo "🎉 Tempest lock release completed!"
    echo "You can now run your tests without lock conflicts."
}

# Run main function
main "$@"