#!/bin/bash
# Setup script for vixy-vision CSI Camera Server

set -e

echo "🦊 Setting up vixy-vision CSI Camera Server..."

# Create virtual environment
python3 -m venv venv
source venv/bin/activate

# Install requirements
pip install --upgrade pip
pip install -r requirements.txt

# Try to install camera library
echo "Detecting camera library..."
if python3 -c "from picamera2 import Picamera2" 2>/dev/null; then
    echo "✓ picamera2 already installed"
elif python3 -c "import picamera" 2>/dev/null; then
    echo "✓ picamera (legacy) already installed"
else
    echo "Attempting to install picamera2..."
    pip install picamera2 2>/dev/null || {
        echo "picamera2 failed, trying picamera..."
        pip install picamera 2>/dev/null || {
            echo "⚠️ No camera library installed. Will use libcamera-still fallback."
        }
    }
fi

# Generate SSL certificates
if [ ! -d "ssl" ]; then
    echo "Generating SSL certificates..."
    mkdir -p ssl
    openssl req -x509 -newkey rsa:4096 \
        -keyout ssl/key.pem -out ssl/cert.pem \
        -days 365 -nodes \
        -subj "/CN=localhost/O=Vixy Vision CSI/C=US"
    echo "✓ SSL certificates generated"
fi

# Create .env if not exists
if [ ! -f ".env" ]; then
    echo "Creating .env file..."
    API_KEY=$(python3 -c "import secrets; print(secrets.token_urlsafe(32))")
    cat > .env << EOF
API_KEY=${API_KEY}
CAMERA_WIDTH=1920
CAMERA_HEIGHT=1080
JPEG_QUALITY=85
CAMERA_ID=garage
ROTATION=0
IR_MODE=true
EOF
    echo "✓ Created .env with API_KEY: ${API_KEY}"
    echo "⚠️ Save this API key!"
fi

echo ""
echo "✓ Setup complete!"
echo ""
echo "To run the server:"
echo "  source venv/bin/activate"
echo "  python3 -m uvicorn main:app --host 0.0.0.0 --port 8443 --ssl-keyfile ssl/key.pem --ssl-certfile ssl/cert.pem"
