#!/bin/bash

# Sophosic-Coder Environment Setup Script
# This script sets up the Python virtual environment and installs dependencies

set -e  # Exit on any error

echo "🚀 Setting up Sophosic-Coder development environment..."

# Check if Python 3.9+ is available (and less than 3.13)
if ! command -v python3 &> /dev/null; then
    echo "❌ Error: Python 3 is required but not installed."
    exit 1
fi

PYTHON_VERSION=$(python3 -c 'import sys; print(".".join(map(str, sys.version_info[:2])))')
REQUIRED_MIN_VERSION="3.9"
REQUIRED_MAX_VERSION="3.13"

if ! python3 -c "import sys; exit(0 if sys.version_info >= (3, 9) else 1)"; then
    echo "❌ Error: Python $REQUIRED_MIN_VERSION or higher is required."
    echo "   Found: Python $PYTHON_VERSION"
    exit 1
fi

# Check if Python 3.13+ and warn about optional dependencies
if python3 -c "import sys; exit(0 if sys.version_info >= (3, 13) else 1)" 2>/dev/null; then
    echo "⚠️  Note: Using Python 3.13+ - some optional dependencies (vllm) may not be available."
    echo "   Core Sophia functionality will work fine with Groq API."
fi

echo "✅ Python $PYTHON_VERSION found"

# Create virtual environment if it doesn't exist
if [ ! -d ".venv" ]; then
    echo "📦 Creating Python virtual environment..."
    python3 -m venv .venv
    echo "✅ Virtual environment created"
else
    echo "📦 Virtual environment already exists"
fi

# Activate virtual environment
echo "🔧 Activating virtual environment..."
source .venv/bin/activate

# Upgrade pip
echo "⬆️ Upgrading pip..."
pip install --upgrade pip

# Install production dependencies
if [ -f "requirements.txt" ]; then
    echo "📥 Installing production dependencies..."
    pip install -r requirements.txt
fi

# Install development dependencies if they exist
if [ -f "requirements-dev.txt" ]; then
    echo "📥 Installing development dependencies..."
    pip install -r requirements-dev.txt
fi

echo ""
echo "🎉 Environment setup complete!"
echo ""
echo "To activate the environment in the future, run:"
echo "  source .venv/bin/activate"
echo ""
echo "To deactivate the environment, run:"
echo "  deactivate"
echo ""

# Check if .env.example exists and remind about environment variables
if [ -f ".env.example" ]; then
    echo "📋 Don't forget to:"
    echo "  1. Copy .env.example to .env"
    echo "  2. Set your GROQ_API_KEY in the .env file"
    echo ""
fi

echo "🏃 You're ready to start developing!"