#!/bin/bash

# AutoBackups Playwright Test Runner Script
# This script sets up the environment and runs Playwright tests

echo "🚀 AutoBackups - Running Playwright E2E Tests"
echo "============================================="

# Check if conda is available
if ! command -v conda &> /dev/null; then
    echo "❌ Conda is not installed or not in PATH"
    echo "Please install Miniconda/Anaconda and ensure it's in your PATH"
    exit 1
fi

# Activate conda environment
echo "📦 Activating conda environment 'autobackups'..."
source $(conda info --base)/etc/profile.d/conda.sh
conda activate autobackups

if [ $? -ne 0 ]; then
    echo "❌ Failed to activate conda environment 'autobackups'"
    echo "Please create the environment first:"
    echo "conda env create -f environment.yml"
    exit 1
fi

# Check if Python dependencies are installed
echo "🔍 Checking Python dependencies..."
python -c "import flask" 2>/dev/null
if [ $? -ne 0 ]; then
    echo "📥 Installing Python dependencies..."
    pip install -r requirements.txt
fi

# Check if Node.js dependencies are installed
if [ ! -d "node_modules" ]; then
    echo "📥 Installing Node.js dependencies..."
    npm install
fi

# Install Playwright browsers if needed
if [ ! -d "node_modules/@playwright" ]; then
    echo "🌐 Installing Playwright browsers..."
    npx playwright install
fi

# Create test results directory
mkdir -p test-results

# Run tests based on arguments
case "$1" in
    "headed")
        echo "🎭 Running tests in headed mode..."
        npx playwright test --headed
        ;;
    "debug")
        echo "🐛 Running tests in debug mode..."
        npx playwright test --debug
        ;;
    "specific")
        if [ -z "$2" ]; then
            echo "❌ Please specify a test file"
            echo "Usage: $0 specific tests/e2e/dashboard.spec.js"
            exit 1
        fi
        echo "🎯 Running specific test: $2"
        npx playwright test "$2"
        ;;
    "report")
        echo "📊 Opening test report..."
        npx playwright show-report
        ;;
    *)
        echo "🏃 Running all tests..."
        npx playwright test
        ;;
esac

exit_code=$?

if [ $exit_code -eq 0 ]; then
    echo "✅ All tests passed!"
else
    echo "❌ Some tests failed. Check the results above."
fi

echo "📊 To view the detailed report, run: npx playwright show-report"
echo "🔍 Test artifacts are saved in: test-results/"

exit $exit_code
