#!/bin/bash
###############################################################################
# AutoRemaster - Easy Start Script
#
# This script provides a convenient way to launch the AutoRemaster application
# with proper environment setup and error handling.
###############################################################################

set -e  # Exit on error

# Color output for better readability
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Change to script directory
cd "$(dirname "$0")"
PROJECT_DIR="$(pwd)"

echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
echo -e "${BLUE}   AutoRemaster - AI Audio Mastering Tool${NC}"
echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
echo ""

# Function to print colored messages
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[✓]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if virtual environment exists
if [ ! -d "venv310" ]; then
    print_error "Virtual environment 'venv310' not found!"
    print_info "Please create the environment first:"
    echo "  conda create -n venv310 python=3.10"
    echo "  conda activate venv310"
    echo "  pip install -r requirements.txt"
    exit 1
fi

print_success "Found virtual environment: venv310"

# Check if Python exists in venv
PYTHON_BIN="${PROJECT_DIR}/venv310/bin/python"
if [ ! -f "$PYTHON_BIN" ]; then
    print_error "Python binary not found at: $PYTHON_BIN"
    exit 1
fi

# Get Python version
PYTHON_VERSION=$($PYTHON_BIN --version 2>&1)
print_info "Using: $PYTHON_VERSION"

# Check for required dependencies
print_info "Checking dependencies..."

REQUIRED_PACKAGES=(
    "customtkinter"
    "numpy"
    "scipy"
    "soundfile"
    "matplotlib"
    "pedalboard"
    "pyloudnorm"
    "pygame"
)

MISSING_PACKAGES=()

for package in "${REQUIRED_PACKAGES[@]}"; do
    if ! $PYTHON_BIN -c "import $package" 2>/dev/null; then
        MISSING_PACKAGES+=("$package")
    fi
done

if [ ${#MISSING_PACKAGES[@]} -gt 0 ]; then
    print_warning "Missing packages detected: ${MISSING_PACKAGES[*]}"
    print_info "Installing missing dependencies..."

    export PATH="${PROJECT_DIR}/venv310/bin:$PATH"
    pip install "${MISSING_PACKAGES[@]}"

    print_success "Dependencies installed"
else
    print_success "All required dependencies found"
fi

# Check for source files
if [ ! -f "src/main.py" ]; then
    print_error "Application source not found: src/main.py"
    exit 1
fi

print_success "Application source found"

# Create temp directory if it doesn't exist
if [ ! -d "temp" ]; then
    print_info "Creating temp directory..."
    mkdir -p temp
fi

# Set up environment variables for better GUI compatibility
export PYTHONUNBUFFERED=1
export DISPLAY="${DISPLAY:-:0}"

# Check if DISPLAY is set (required for GUI)
if [ -z "$DISPLAY" ]; then
    print_warning "DISPLAY environment variable not set"
    print_info "Setting DISPLAY=:0 (default X server)"
fi

# Optional: Set matplotlib backend to avoid threading issues
export MPLBACKEND=TkAgg

print_success "Environment configured"
echo ""
print_info "Starting AutoRemaster..."
echo ""

# Launch the application
exec $PYTHON_BIN src/main.py "$@"
