#!/bin/bash

# Script to run the annotation GUI with automatic virtual environment detection

# Get the directory of this script
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Change to the script directory
cd "$SCRIPT_DIR"

# Function to check if a command exists
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# Check for Python
if ! command_exists python; then
    echo "Error: Python is not installed or not in PATH"
    exit 1
fi

# Check for virtual environment
VENV_DIR=""
if [ -d "venv" ]; then
    VENV_DIR="venv"
elif [ -d ".venv" ]; then
    VENV_DIR=".venv"
elif [ -d "env" ]; then
    VENV_DIR="env"
fi

# Check for conda environment
CONDA_ENV=""
if command_exists conda; then
    # Check if we're already in a conda environment
    if [ -n "$CONDA_DEFAULT_ENV" ]; then
        CONDA_ENV="$CONDA_DEFAULT_ENV"
    else
        # Try to find a conda environment with the project name
        PROJECT_NAME=$(basename "$SCRIPT_DIR")
        if conda env list | grep -q "^$PROJECT_NAME "; then
            CONDA_ENV="$PROJECT_NAME"
        fi
    fi
fi

# Activate virtual environment
if [ -n "$VENV_DIR" ]; then
    echo "Activating virtual environment: $VENV_DIR"
    source "$VENV_DIR/bin/activate"
elif [ -n "$CONDA_ENV" ]; then
    echo "Activating conda environment: $CONDA_ENV"
    conda activate "$CONDA_ENV"
else
    echo "Warning: No virtual environment found. Using system Python."
    echo "Consider creating a virtual environment with:"
    echo "  python -m venv venv"
    echo "  source venv/bin/activate"
    echo "  pip install -r requirements.txt"
fi

# Check if requirements are installed
echo "Checking if dependencies are installed..."
python -c "
import sys
try:
    import gradio
    import torch
    import PIL
    print('✓ Core dependencies are installed')
except ImportError as e:
    print(f'✗ Missing dependency: {e}')
    print('Installing requirements...')
    import subprocess
    result = subprocess.run([sys.executable, '-m', 'pip', 'install', '-r', 'requirements.txt'], 
                          capture_output=True, text=True)
    if result.returncode != 0:
        print('Failed to install requirements:')
        print(result.stderr)
        sys.exit(1)
    else:
        print('✓ Requirements installed successfully')
"

# Run the GUI
echo "Starting annotation GUI..."
python annotation_gui.py "$@"

# Deactivate virtual environment if activated
if [ -n "$VENV_DIR" ] || [ -n "$CONDA_ENV" ]; then
    if [ -n "$VENV_DIR" ]; then
        deactivate
    elif [ -n "$CONDA_ENV" ]; then
        conda deactivate
    fi
fi