# Railway Environment Variables Setup Guide

**Quick Reference for Configuring Production Environment**

This guide provides step-by-step instructions for configuring the required environment variables on Railway to enable bot spawning functionality.

---

## Why This Is Needed

Railway deployments **do not automatically inherit** environment variables from:
- Local `.env` files
- Git repository `.env` files
- Local development environment

Environment variables must be **manually configured** in Railway for security and isolation between environments.

---

## Required Environment Variables

### 🔴 Critical (Required for Bot Spawning)

| Variable | Purpose | Where to Get It |
|----------|---------|-----------------|
| `DAILY_PIPECAT_API_KEY` | Pipecat integration with Daily.co | Daily.co Dashboard → API Keys |
| `DAILY_API_KEY` | Daily.co room creation and management | Daily.co Dashboard → API Keys |
| `SUPABASE_URL` | Supabase project URL | Supabase Dashboard → Project Settings |
| `SUPABASE_SERVICE_KEY` | Supabase admin operations | Supabase Dashboard → Project Settings → API |

### 🟡 Optional (Features Work Without)

| Variable | Purpose | Default |
|----------|---------|---------|
| `PIPECAT_API_KEY` | Additional Pipecat auth (if different) | Falls back to DAILY_PIPECAT_API_KEY |
| `BOT_TIMEOUT_MINUTES` | Maximum bot session duration | 30 minutes |
| `MAX_CONCURRENT_BOTS` | Max number of simultaneous bots | 5 |
| `FRAME_RATE` | Video streaming frame rate | 10 FPS |
| `LOG_LEVEL` | Logging verbosity | INFO |

---

## Setup Methods

### Method 1: Railway Dashboard (Recommended)

**Time**: 5 minutes | **Difficulty**: Easy

#### Step 1: Access Railway Project

1. Go to https://railway.app
2. Log in with your account
3. Find the `slide-system-production` project
4. Click on the project

#### Step 2: Open Variables

1. Click on your service (e.g., `slide-system`)
2. Navigate to the **Variables** tab
3. You'll see a list of environment variables

#### Step 3: Add Variables

For each required variable:

1. Click **+ New Variable**
2. Enter **Variable Name** (e.g., `DAILY_PIPECAT_API_KEY`)
3. Enter **Value** (paste your API key)
4. Click **Add**

#### Step 4: Verify and Deploy

1. Check that all 4 critical variables are added
2. Railway will automatically redeploy (or click **Deploy**)
3. Wait ~3-5 minutes for deployment
4. Verify with health check
**Verification**:
```bash
curl https://slide-system-production-5813.up.railway.app/health
# Should return 200 OK
```

---

### Method 2: Railway CLI

**Time**: 3 minutes | **Difficulty**: Medium | **Requires**: Railway CLI installed

#### Step 1: Install Railway CLI

```bash
# macOS/Linux
curl -fsSL https://railway.app/install.sh | sh

# Or via npm
npm install -g @railway/cli

# Or via Homebrew
brew install railway
```

#### Step 2: Login and Link

```bash
# Login to Railway
railway login

# Link to your project
railway link
# Select: slide-system-production
```

#### Step 3: Set Variables

```bash
# Set DAILY_PIPECAT_API_KEY
railway variables set DAILY_PIPECAT_API_KEY="<your-pipecat-key>"

# Set DAILY_API_KEY
railway variables set DAILY_API_KEY="<your-daily-key>"

# Set SUPABASE_URL
railway variables set SUPABASE_URL="<your-supabase-url>"

# Set SUPABASE_SERVICE_KEY
railway variables set SUPABASE_SERVICE_KEY="<your-supabase-service-key>"
```

#### Step 4: Verify Variables

```bash
# List all variables
railway variables

# Should show:
# DAILY_PIPECAT_API_KEY: <hidden>
# DAILY_API_KEY: <hidden>
# SUPABASE_URL: https://...
# SUPABASE_SERVICE_KEY: <hidden>
```

#### Step 5: Trigger Deployment

```bash
# Railway auto-deploys on variable changes, but you can force it:
railway up --detach
```

---

### Method 3: Environment Variable File (Local Reference Only)

**DO NOT** commit this to Git!

Create a local reference file to copy-paste from:

**File**: `.env.railway.local` (gitignored)

```bash
# Railway Environment Variables
# Copy-paste these into Railway dashboard
# DO NOT commit this file to Git!

# Daily.co Integration
DAILY_PIPECAT_API_KEY=your-pipecat-key-here
DAILY_API_KEY=your-daily-api-key-here

# Supabase
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_SERVICE_KEY=your-service-key-here

# Optional
BOT_TIMEOUT_MINUTES=30
MAX_CONCURRENT_BOTS=5
FRAME_RATE=10
LOG_LEVEL=INFO
```

**Important**: Add to `.gitignore`:
```bash
echo ".env.railway.local" >> .gitignore
```

---

## Obtaining API Keys

### Daily.co API Keys

1. Go to https://dashboard.daily.co
2. Log in to your account
3. Navigate to **Developers** → **API Keys**
4. Find or create:
   - **Daily API Key**: For room creation
   - **Pipecat API Key**: For bot integration (may be same key)
5. Copy the keys (you won't be able to see them again)

**Note**: If you don't have a Pipecat-specific key, use your Daily API key for both `DAILY_API_KEY` and `DAILY_PIPECAT_API_KEY`.

### Supabase Credentials

1. Go to https://app.supabase.com
2. Open your project (or create one)
3. Navigate to **Settings** → **API**
4. Copy:
   - **Project URL**: `SUPABASE_URL`
   - **Service Role Key**: `SUPABASE_SERVICE_KEY` (not anon key!)
5. ⚠️ Use the **service_role** key, not the **anon** key!

**Security Note**: The service_role key has admin privileges. Never expose it in client-side code.

---

## Validation

### Step 1: Check Variables Are Set

**Railway Dashboard**:
- Go to Variables tab
- Verify all 4 critical variables show as configured
- Values will be hidden for security

**Railway CLI**:
```bash
railway variables
```

### Step 2: Test Bot Spawn Endpoint

Once variables are configured and deployed:

```bash
# Generate session ID
SESSION_ID=$(python3 -c "import uuid; print(uuid.uuid4())")
# Test spawn endpoint
curl -X POST https://slide-system-production-5813.up.railway.app/api/bots/screenshare/spawn \
  -H "Content-Type: application/json" \
  -d "{
    \"room_url\": \"https://buzztrail.daily.co/test-room\",
    \"deck_url\": \"https://buzztrail.github.io/buzztrail-presentations/p10e-2f8z-h0fi/\",
    \"session_id\": \"$SESSION_ID\"
  }"
```

**Expected Response** (if configured correctly):
```json
{
  "bot_id": "550e8400-e29b-41d4-a716-446655440000",
  "status": "spawning",
  "pid": 12345,
  "estimated_join_time": "5s",
  "message": "Bot spawned successfully for session ..."
}
```

**Error Response** (if still missing variables):
```json
{
  "error": "Server configuration error",
  "details": "DAILY_PIPECAT_API_KEY not configured"
}
```

### Step 3: Check Railway Logs

```bash
# Via CLI
railway logs --follow

# Or via Dashboard
# Go to project → Deployments → Latest → Logs
```

Look for:
- ✅ `[ScreenshareBotSpawn] Spawn request:` - Endpoint working
- ✅ `[ScreenshareBotManager] Bot spawned:` - Bot created successfully
- ❌ `DAILY_PIPECAT_API_KEY not configured` - Variables missing

---

## Troubleshooting

### Issue: Variables Set But Still Get Error

**Symptoms**:
```json
{"error":"Server configuration error","details":"DAILY_PIPECAT_API_KEY not configured"}
```

**Solutions**:
1. **Trigger redeploy**: Railway caches environment at build time
   ```bash
   railway up --detach
   # Or: Railway Dashboard → Deployments → Redeploy
   ```

2. **Check variable names**: Must be exact (case-sensitive)
   - ✅ `DAILY_PIPECAT_API_KEY`
   - ❌ `DAILY_PIPECAT_API_KEY_` (trailing underscore)
   - ❌ `daily_pipecat_api_key` (wrong case)

3. **Verify service**: Make sure variables are set on correct service
   - Check: Railway Dashboard → Select Service → Variables

### Issue: Supabase Connection Fails

**Symptoms**:
```
Failed to connect to Supabase: Connection refused
```

**Solutions**:
1. **Check URL format**:
   - ✅ `https://your-project.supabase.co`
   - ❌ `https://your-project.supabase.co/` (trailing slash)

2. **Verify key is service_role**:
   - Should start with `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...`
   - NOT the anon key

3. **Test connection**:
   ```bash
   curl -X GET https://your-project.supabase.co/rest/v1/ \
     -H "apikey: your-service-key" \
     -H "Authorization: Bearer your-service-key"
   ```

### Issue: Daily.co API Key Invalid

**Symptoms**:
```
Daily.co API error: Unauthorized
```

**Solutions**:
1. **Regenerate key**: Go to Daily.co dashboard and create new key
2. **Check key format**: Should be a long alphanumeric string
3. **Verify permissions**: Key must have `createRoom` permission

---

## Security Best Practices

### 🔐 DO

- ✅ Use Railway dashboard or CLI to set variables
- ✅ Use different keys for dev/staging/production
- ✅ Rotate keys every 90 days
- ✅ Restrict Daily.co key permissions to minimum required
- ✅ Use Supabase Row Level Security (RLS)
- ✅ Monitor Railway logs for unauthorized access

### ❌ DON'T

- ❌ Commit `.env` files to git
- ❌ Share production keys via chat/email
- ❌ Use production keys for local development
- ❌ Hardcode keys in source code
- ❌ Expose service_role key in client-side code
- ❌ Use same keys across all environments

### Key Rotation

**Every 90 days**:
1. Generate new API keys in Daily.co/Supabase dashboards
2. Update Railway variables with new keys
3. Wait for deployment to complete
4. Revoke old keys
5. Test bot spawning with new keys

---

## Quick Reference Commands

### Railway CLI Setup

```bash
# Install
npm install -g @railway/cli

# Login
railway login

# Link project
railway link

# Set variable
railway variables set KEY="value"

# List variables
railway variables

# View logs
railway logs --follow

# Deploy
railway up --detach
```

### Testing
```bash
# Health check
curl https://slide-system-production-5813.up.railway.app/health
# Test bot spawn
SESSION_ID=$(python3 -c "import uuid; print(uuid.uuid4())")
curl -X POST https://slide-system-production-5813.up.railway.app/api/bots/screenshare/spawn \
  -H "Content-Type: application/json" \
  -d "{
    \"room_url\": \"https://buzztrail.daily.co/test\",
    \"deck_url\": \"https://buzztrail.github.io/buzztrail-presentations/p10e-2f8z-h0fi/\",
    \"session_id\": \"$SESSION_ID\"
  }"
# Check bot status
curl https://slide-system-production-5813.up.railway.app/api/bots/screenshare/status
# Kill bot
curl -X POST https://slide-system-production-5813.up.railway.app/api/bots/screenshare/kill/<bot-id>
```

---

## Next Steps

After environment variables are configured:

1. ✅ **Verify deployment**: Check Railway logs for startup errors
2. ✅ **Test bot spawn**: Use curl commands above
3. ✅ **Run lifecycle test**: Full spawn→run→kill test
4. ✅ **Monitor performance**: Watch Railway metrics
5. ✅ **Configure alerts**: Set up notifications for failures

---

## Support

- **Railway Docs**: https://docs.railway.app/develop/variables
- **Daily.co Docs**: https://docs.daily.co/reference/rest-api
- **Supabase Docs**: https://supabase.com/docs/guides/api
- **Project Issues**: https://github.com/BuzzTrail/video-extension/issues

---

**Last Updated**: 2025-10-12
**Deployment**: Railway Production
**Project**: slide-system-production
