# Local Testing vs Railway Deployment - Parity Analysis

## Current Status

### ✅ Already Identical
1. **Python Environment**: Same `uv`-managed `.venv` (Python 3.14.0)
2. **Dependencies**: Same packages from `uv.lock`
3. **Bot Code**: Same `bot.py` execution

### ❌ Key Differences

| Aspect | Local Test | Railway Production | Impact |
|--------|-----------|-------------------|---------|
| **Environment Variables** | None set | Full set (LIVEKIT_*, SUPABASE_*) | Medium |
| **Working Directory** | `bots/screenshare-bot/` | `/app/bots/screenshare-bot/` | Low |
| **Process Spawning** | Direct execution | Node.js `spawn()` with detached process | Medium |
| **Logging** | Console only | Console + log files + Railway logs | High |
| **Playwright Browsers** | Manually installed | Pre-installed in Docker (`--with-deps`) | Critical |
| **System Dependencies** | May be missing | All deps in Docker (libnss3, libglib, etc.) | Critical |

## Recommended Improvements

### 1. Environment Variables (HIGH PRIORITY)

**Problem**: Local test doesn't set environment variables that Railway provides

**Solution**: Create `.env.local` file for local testing

```bash
# .env.local (for local bot testing)
TRANSPORT_TYPE=livekit
LIVEKIT_URL=wss://your-project.livekit.cloud
LIVEKIT_API_KEY=your_api_key
LIVEKIT_API_SECRET=your_api_secret
LIVEKIT_ROOM_NAME=test-room
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_SERVICE_KEY=your_service_key
PYTHONUNBUFFERED=1
```

**Update test script** to load env vars:
```python
# At top of test_local_capture.py
from dotenv import load_dotenv
load_dotenv('.env.local')  # Load local environment
```

### 2. Playwright Browser Installation (CRITICAL)

**Problem**: Local may be missing browser binaries or system dependencies

**Railway Setup**:
```dockerfile
# Dockerfile line 37
RUN /app/.venv/bin/playwright install --with-deps chromium
```

**Local Setup**:
```bash
# Run this once locally
.venv/bin/playwright install --with-deps chromium
```

### 3. Working Directory Parity (LOW PRIORITY)

**Problem**: Paths differ (`bots/screenshare-bot/` vs `/app/bots/screenshare-bot/`)

**Solution**: Test script already uses relative paths, so this is fine

### 4. Process Spawning Simulation (MEDIUM PRIORITY)

**Problem**: Railway spawns bot as detached child process with specific env vars

**Railway Spawn** (from `bot-spawn-livekit.step.ts:157-172`):
```typescript
const botProcess = spawn(pythonCmd, args, {
  env: {
    ...process.env,
    TRANSPORT_TYPE: 'livekit',
    LIVEKIT_URL: livekitUrl,
    LIVEKIT_ROOM_NAME: room_name,
    LIVEKIT_API_KEY: process.env.LIVEKIT_API_KEY,
    LIVEKIT_API_SECRET: process.env.LIVEKIT_API_SECRET,
    SUPABASE_URL: process.env.SUPABASE_URL,
    SUPABASE_SERVICE_KEY: process.env.SUPABASE_SERVICE_KEY,
    PYTHONUNBUFFERED: '1',
  },
  cwd: '/app/bots/screenshare-bot',
  stdio: ['ignore', 'pipe', 'pipe'],
  detached: true,
});
```

**Local Simulation**: Create shell script that mimics this:

```bash
#!/bin/bash
# test_railway_spawn.sh - Simulates Railway spawn locally

# Load env vars
source .env.local

# Export env vars (same as Railway)
export TRANSPORT_TYPE=livekit
export LIVEKIT_URL=$LIVEKIT_URL
export LIVEKIT_ROOM_NAME=$LIVEKIT_ROOM_NAME
export LIVEKIT_API_KEY=$LIVEKIT_API_KEY
export LIVEKIT_API_SECRET=$LIVEKIT_API_SECRET
export SUPABASE_URL=$SUPABASE_URL
export SUPABASE_SERVICE_KEY=$SUPABASE_SERVICE_KEY
export PYTHONUNBUFFERED=1

# Run bot (same command as Railway)
.venv/bin/python bot.py \\
  "$LIVEKIT_URL/$LIVEKIT_ROOM_NAME" \\
  "https://buzztrail.github.io/buzztrail-presentations/p10e-2f8z-h0fi/" \\
  "test-session-123" \\
  "test-bot-456" \\
  "" \\
  "$LIVEKIT_TOKEN"
```

### 5. Logging Parity (HIGH PRIORITY)

**Problem**: Railway logs to file + console, local only logs to console

**Railway Logging** (from `bot-spawn-livekit.step.ts:187-198`):
```typescript
botProcess.stdout?.on('data', (data) => {
  logStream.write(`[STDOUT] ${output}`);
  console.log(`[Bot ${botId} STDOUT]`, output.trim());
});
```

**Local Logging**: Update test script to write to log file:

```python
# In test_local_capture.py
import sys
from datetime import datetime

# Create log file
log_dir = Path("./test_logs")
log_dir.mkdir(exist_ok=True)
log_file = log_dir / f"bot-test-{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"

class TeeLogger:
    """Write to both console and file (like Railway)"""
    def __init__(self, file_path):
        self.terminal = sys.stdout
        self.log = open(file_path, 'a')

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)

    def flush(self):
        self.terminal.flush()
        self.log.flush()

# Redirect stdout to both console and file
sys.stdout = TeeLogger(log_file)
sys.stderr = TeeLogger(log_file)
```

### 6. Full Integration Test (HIGHEST PRIORITY)

**Create `test_full_integration.py`** that mimics Railway completely:

```python
#!/usr/bin/env python3
"""
Full Integration Test - Railway Parity

Simulates exactly how Railway spawns and runs the bot:
1. Loads environment variables
2. Spawns detached process
3. Logs to file + console
4. Uses LiveKit room (if configured)
"""

import asyncio
import os
import sys
import subprocess
from pathlib import Path
from datetime import datetime
from dotenv import load_dotenv

async def main():
    # Load env vars (like Railway)
    load_dotenv('.env.local')

    # Prepare paths (like Railway)
    bot_script = Path(__file__).parent / "bot.py"
    venv_python = Path(__file__).parent / ".venv/bin/python"

    # Prepare log file (like Railway)
    log_dir = Path("./test_logs")
    log_dir.mkdir(exist_ok=True)
    log_file = log_dir / f"bot-{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"

    # Build command (like Railway)
    room_url = f"{os.getenv('LIVEKIT_URL')}/{os.getenv('LIVEKIT_ROOM_NAME', 'test-room')}"
    deck_url = "https://buzztrail.github.io/buzztrail-presentations/p10e-2f8z-h0fi/"
    session_id = "test-session-123"
    bot_id = "test-bot-456"

    args = [
        str(venv_python),
        str(bot_script),
        room_url,
        deck_url,
        session_id,
        bot_id,
        "",  # deck_id (empty)
        os.getenv('LIVEKIT_TOKEN', ''),  # access token
    ]

    # Prepare env vars (like Railway)
    env = os.environ.copy()
    env.update({
        'TRANSPORT_TYPE': 'livekit',
        'LIVEKIT_URL': os.getenv('LIVEKIT_URL'),
        'LIVEKIT_ROOM_NAME': os.getenv('LIVEKIT_ROOM_NAME', 'test-room'),
        'LIVEKIT_API_KEY': os.getenv('LIVEKIT_API_KEY'),
        'LIVEKIT_API_SECRET': os.getenv('LIVEKIT_API_SECRET'),
        'SUPABASE_URL': os.getenv('SUPABASE_URL'),
        'SUPABASE_SERVICE_KEY': os.getenv('SUPABASE_SERVICE_KEY'),
        'PYTHONUNBUFFERED': '1',
    })

    print(f"[IntegrationTest] Starting bot with Railway-like spawn")
    print(f"[IntegrationTest] Log file: {log_file}")
    print(f"[IntegrationTest] Room: {room_url}")
    print(f"[IntegrationTest] Deck: {deck_url}")
    print()

    # Spawn process (like Railway)
    with open(log_file, 'w') as log:
        process = subprocess.Popen(
            args,
            env=env,
            cwd=str(Path(__file__).parent),
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
        )

        print(f"[IntegrationTest] Bot spawned with PID: {process.pid}")

        # Stream output (like Railway)
        while True:
            output = process.stdout.readline()
            if output:
                log.write(f"[STDOUT] {output}")
                log.flush()
                print(f"[Bot STDOUT] {output.strip()}")

            err = process.stderr.readline()
            if err:
                log.write(f"[STDERR] {err}")
                log.flush()
                print(f"[Bot STDERR] {err.strip()}")

            # Check if process ended
            if output == '' and err == '' and process.poll() is not None:
                break

        exit_code = process.wait()
        print(f"\\n[IntegrationTest] Bot exited with code: {exit_code}")

if __name__ == "__main__":
    asyncio.run(main())
```

## Implementation Checklist

- [ ] Create `.env.local` with all Railway environment variables
- [ ] Install Playwright browsers locally: `.venv/bin/playwright install --with-deps chromium`
- [ ] Update `test_local_capture.py` to load `.env.local`
- [ ] Add logging to file (TeeLogger class)
- [ ] Create `test_railway_spawn.sh` script
- [ ] Create `test_full_integration.py` script
- [ ] Test with real LiveKit room (if available)
- [ ] Document differences that can't be eliminated (e.g., container vs host OS)

## Remaining Unavoidable Differences

1. **Container vs Host OS**: Railway runs in Docker container (Debian-based), local runs on host OS (macOS/Linux/Windows)
2. **Network**: Railway has different network topology
3. **File Paths**: `/app/` prefix in Railway vs local paths
4. **Process Management**: Railway uses systemd/Docker process management

These differences are minimal and shouldn't affect bot behavior if the above improvements are implemented.
