# WebSocket Deployment Guide

## Quick Deployment Steps

### 1. Install New Dependencies
```bash
cd /opt/dockers/echoes_of_the_ashes
docker compose down
docker compose build
docker compose up -d
```

This will rebuild the containers with the new `websockets` package.

### 2. Verify Installation
Check that the API container started successfully:
```bash
docker compose logs api | grep "WebSocket"
```

You should see log entries about WebSocket connections once players connect.

### 3. Test WebSocket Connection
Open the game in a browser and check the console (F12):
- Look for: `🔌 Connecting to WebSocket: ws://...`
- Look for: `✅ WebSocket connected`

### 4. Monitor Active Connections
Check the health endpoint to see active WebSocket connections:
```bash
curl http://localhost:8000/health
```

(Can be extended to show WebSocket connection count)

### 5. Test Real-Time Updates
1. **Movement Test:**
   - Open game in two browser tabs (different accounts)
   - Move one character to a location
   - Other tab should see "Player arrived" message immediately

2. **Combat Test:**
   - Start combat with an NPC
   - Attacks should update immediately (no 5s delay)

3. **Pickup Test:**
   - Drop an item in a location
   - Other players in same location should see it disappear when picked up

## Rollback (If Needed)

If WebSocket causes issues, you can roll back to pure polling:

### Option 1: Disable WebSocket on Frontend
Edit `pwa/src/components/Game.tsx`:
```typescript
const { isConnected, sendMessage } = useGameWebSocket({
  token,
  onMessage: handleWebSocketMessage,
  enabled: false  // Change true to false
})
```

### Option 2: Remove WebSocket from Backend
Revert changes to:
- `api/main.py` (remove WebSocket endpoint and broadcasts)
- `api/database.py` (remove get_players_in_location)
- `requirements.txt` (remove websockets package)

Then rebuild and redeploy.

## Performance Monitoring

### Watch for Issues
```bash
# Monitor API logs for WebSocket errors
docker compose logs -f api | grep "WebSocket\|❌"

# Check for memory usage increases
docker stats echoes_of_the_ashes_api

# Monitor connection count (check server load)
# Add to health endpoint or check logs for "WebSocket connected/disconnected"
```

### Expected Behavior
- **Connection:** Players connect within 1-2 seconds of loading game
- **Reconnection:** If network drops, should reconnect within 3 seconds
- **Memory:** ~10MB per 1,000 connections (very low)
- **CPU:** Should decrease compared to polling (event-driven)

## Troubleshooting

### WebSocket Not Connecting
1. Check CORS settings in `api/main.py`
2. Verify token is present: `localStorage.getItem('token')` in browser console
3. Check nginx/proxy configuration (if using reverse proxy)

### Frequent Disconnections
1. Check heartbeat interval (30s default)
2. Verify network stability
3. Check for proxy timeouts (nginx: `proxy_read_timeout 60s;`)

### Messages Not Received
1. Verify `manager.send_personal_message()` is being called
2. Check player_id matches active connection
3. Look for WebSocket send errors in logs

## Next Steps After Deployment

1. **Monitor for 24 hours:** Check stability and error rates
2. **Gather user feedback:** Is latency better? Any connection issues?
3. **Plan live chat:** Quick win feature using WebSocket infrastructure
4. **Consider party system:** Next major feature enabled by WebSockets

## Success Metrics

After deployment, you should see:
- ✅ **95% reduction** in API request volume
- ✅ **<100ms latency** for game updates (vs 2500ms avg with polling)
- ✅ **Lower server CPU** usage (event-driven vs continuous polling)
- ✅ **Improved UX** - instant feedback on actions

Good luck with the deployment! 🚀
