#!/bin/bash
# SHARP Studio - One-Click Setup for Mac
# Double-click this file from anywhere - it sets up everything automatically!

set -e

echo ""
echo "🎨 SHARP Studio - 3D Gaussian Splatting from Photos"
echo "===================================================="
echo ""

# Install location (in user's home folder)
APP_DIR="$HOME/SharpStudio"

# Check for Python
if ! command -v python3 &> /dev/null; then
    echo "❌ Python 3 not found."
    echo ""
    echo "Please install Python 3.10+ from:"
    echo "   https://www.python.org/downloads/"
    echo ""
    echo "Or install via Homebrew:"
    echo "   /bin/bash -c \"\$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\""
    echo "   brew install python3"
    echo ""
    read -p "Press Enter to exit..."
    exit 1
fi

# Create app directory
echo "📂 Setting up in: $APP_DIR"
mkdir -p "$APP_DIR"
cd "$APP_DIR"

# Download project if not present
if [ ! -f "server.py" ]; then
    echo "⬇️  Downloading SHARP Studio code..."
    curl -sL https://github.com/apple/ml-sharp/archive/refs/heads/main.zip -o sharp.zip
    unzip -q sharp.zip
    mv ml-sharp-main/* . 2>/dev/null || true
    rm -rf ml-sharp-main sharp.zip
fi

# Create virtual environment
if [ ! -d "venv" ]; then
    echo "📦 Creating Python environment..."
    python3 -m venv venv
fi

source venv/bin/activate

# Install dependencies
echo "📥 Installing dependencies..."
pip install -q --upgrade pip
pip install -q torch torchvision fastapi uvicorn pillow numpy

# Download model if not present
if [ ! -f "sharp_model.pt" ]; then
    echo ""
    echo "⬇️  Downloading AI model from Apple (~2.6GB)..."
    echo "   This only happens once, please wait..."
    curl -L "https://ml-site.cdn-apple.com/models/sharp/sharp_2572gikvuh.pt" -o sharp_model.pt
fi

echo ""
echo "✅ Setup complete!"
echo "   App location: $APP_DIR"
echo ""
echo "🚀 Starting SHARP Studio..."
echo "   Opening browser to http://localhost:8000"
echo ""
echo "   Press Ctrl+C to stop the server"
echo ""

# Open browser after short delay
(sleep 3 && open "http://localhost:8000") &

# Start server
python -m uvicorn server:app --host 0.0.0.0 --port 8000
