# Quick Start Guide: Phases 5-7 Components

## Installation & Setup

### 1. Install Dependencies
```bash
cd /home/user/lichun/ws
pip install sentry-sdk psutil
```

### 2. Verify Installation
```bash
python test_new_components.py
```

Expected output: `✓ ALL TESTS PASSED - Components are ready to use!`

### 3. Database Setup
```bash
# Run these SQL scripts to create required tables
mysql -u your_user -p lifesim < sql/analytics_tables.sql
mysql -u your_user -p lifesim < sql/gdpr_tables.sql
```

(SQL scripts are documented in docs/archived/PHASES_5-7_IMPLEMENTATION_SUMMARY.md)

---

## Quick Integration Examples

### Example 1: Add Analytics to Existing Events

**File:** `ws/events.py`

```python
# At the top of the file
from analytics.events import track_event, track_purchase_completed

# In your event functions
def birthdayEvent(player):
    # ... existing code ...

    # Add analytics tracking
    track_event(player.c.userID, 'birthday_celebrated', {
        'age': player.c.age,
        'location': player.c.currentLocation.type if player.c.currentLocation else None
    })

    return message
```

### Example 2: Add Performance Monitoring to Critical Functions

**File:** `ws/functions.py`

```python
# At the top of the file
from monitoring.performance import measure_performance

# Add decorator to functions
@measure_performance()
def loadGame(userID):
    # ... existing code ...
    return player

@measure_performance()
def saveGame(player):
    # ... existing code ...
    pass
```

### Example 3: Enable Player Data Caching

**File:** `ws/app.py`

```python
# At the top of the file
from performance.caching import player_cache

# In initLifeSim function
async def initLifeSim(websocket, oneTimePlayer=False):
    # Try to get from cache first
    player = player_cache.get(websocket.userID)

    if not player:
        # Load from database
        player = playerRecords[websocket.userID]
        # Cache for future requests
        player_cache.set(websocket.userID, player)

    # ... rest of your code ...
```

### Example 4: Add Health Check Endpoint

**File:** `ws/app.py`

```python
# At the top of the file
from deployment.health_check import get_health_checker
import json

# Initialize health checker
health_checker = get_health_checker(mydb)

# Add health check handler
async def health_check_handler(websocket, path):
    """Handle health check requests."""
    active_connections = len(USERS)
    health_status = health_checker.perform_full_check(active_connections)

    response = json.dumps(health_status)
    await websocket.send(response)
    await websocket.close()

# Modify your WebSocket server (in main())
async def handle_connection(websocket, path):
    if path == '/health':
        await health_check_handler(websocket, path)
    else:
        await consumer(websocket, path)

# Update server start
async with websockets.serve(handle_connection, "0.0.0.0", 8001):
    await asyncio.Future()
```

### Example 5: Enable A/B Testing for Features

**File:** `ws/tutorial_events.py`

```python
# At the top of the file
from experiments.ab_testing import get_variant

def show_tutorial(player):
    """Show tutorial based on A/B test variant."""
    variant = get_variant(player.c.userID, 'tutorial_flow')

    if variant == 'treatment':
        # Show new tutorial
        return show_new_tutorial_flow(player)
    else:
        # Show original tutorial
        return show_original_tutorial_flow(player)
```

### Example 6: Initialize Sentry on Startup

**File:** `ws/app.py` (at the very top, after imports)

```python
# Initialize Sentry for error tracking
from monitoring.sentry_setup import init_sentry
import os

# Initialize Sentry (only in production)
if os.getenv('ENVIRONMENT') == 'production':
    init_sentry(
        environment='production',
        release='1.0.0'
    )
```

### Example 7: Add GDPR Data Export Endpoint

**File:** `ws/app.py` (in consumer function)

```python
from api.data_management import export_user_data

async def consumer(websocket, path):
    # ... existing code ...

    # Add new message type handler
    elif message_type == 'export_data':
        try:
            # Export user data
            json_data = export_user_data(websocket.userID, mydb)

            # Send to client
            await websocket.send(json.dumps({
                'type': 'data_export',
                'data': json_data
            }))
        except Exception as e:
            logger.error(f"Data export failed: {e}")
```

---

## Environment Variables to Add

Create or update `.env` file:

```bash
# Sentry Error Tracking
SENTRY_DSN=https://your-sentry-dsn-here
SENTRY_ENVIRONMENT=production
SENTRY_RELEASE=1.0.0

# Database (if not already set)
DB_HOST=localhost
DB_PORT=3306
DB_USER=your_user
DB_PASSWORD=your_password
DB_NAME=lifesim

# Feature Flags (optional)
ENABLE_ANALYTICS=true
ENABLE_AB_TESTING=true
```

---

## Cron Jobs to Schedule

### 1. Daily Account Cleanup (Required for GDPR)

Create file: `/home/user/lichun/ws/cron_cleanup.py`

```python
#!/usr/bin/env python
import sys
sys.path.insert(0, '/home/user/lichun/ws')

from functions import connect_to_database
from api.data_management import get_data_service

# Run cleanup
mydb = connect_to_database()
service = get_data_service(mydb)
deleted_count = service.hard_delete_expired_accounts()
print(f"Deleted {deleted_count} expired accounts")
```

Add to crontab:
```bash
# Daily at 2 AM
0 2 * * * cd /home/user/lichun/ws && python cron_cleanup.py >> /var/log/baolife_cleanup.log 2>&1
```

### 2. Performance Report (Optional)

```bash
# Every 6 hours
0 */6 * * * cd /home/user/lichun/ws && python -c "from monitoring.performance import log_performance_report; log_performance_report()" >> /var/log/baolife_performance.log 2>&1
```

---

## Monitoring Dashboard Setup

### Key Metrics to Monitor:

1. **Performance Metrics** (from `monitoring.performance`)
   - Average operation duration
   - P95/P99 latency
   - Slow operations (> 1s)

2. **Cache Metrics** (from `performance.caching`)
   - Cache hit rate
   - Cache size utilization
   - Eviction rate

3. **Health Metrics** (from `deployment.health_check`)
   - Database latency
   - Memory usage
   - Disk usage
   - WebSocket connections

4. **Analytics Events** (from `analytics.events`)
   - Events per hour
   - Session duration
   - User engagement

### Access Health Status:

```bash
# WebSocket health check
wscat -c ws://localhost:8001/health

# Or via Python
python -c "import asyncio; from deployment.health_check import get_health_checker, connect_to_database; hc = get_health_checker(connect_to_database()); print(hc.perform_full_check())"
```

---

## Testing Checklist

Before deploying to production:

- [ ] Run `python test_new_components.py` - All tests pass
- [ ] Database tables created (analytics_events, analytics_sessions, deletion_log)
- [ ] Dependencies installed (sentry-sdk, psutil)
- [ ] Environment variables configured
- [ ] Cron jobs scheduled
- [ ] Health check endpoint accessible
- [ ] Sentry integration verified (check Sentry dashboard)
- [ ] Legal documents published (/static/privacy.html, /static/terms.html)
- [ ] GDPR export/delete tested with test account
- [ ] A/B test variants distributing correctly
- [ ] Analytics events appearing in database
- [ ] Performance monitoring tracking operations
- [ ] Cache hit rates acceptable (> 50%)

---

## Troubleshooting

### Issue: "Sentry SDK not installed"
**Solution:** `pip install sentry-sdk`

### Issue: "psutil module not found"
**Solution:** `pip install psutil`

### Issue: Analytics events not appearing in database
**Solution:**
1. Check database connection
2. Verify tables created: `SHOW TABLES LIKE 'analytics%';`
3. Check buffer hasn't filled yet (flushes at 100 events)
4. Manually flush: `tracker._flush_events()`

### Issue: Health check returns "unhealthy"
**Solution:**
1. Check database connection
2. Check memory/disk usage on server
3. Review individual check status in response
4. Adjust thresholds if needed

### Issue: GDPR export failing
**Solution:**
1. Verify all required tables exist
2. Check database permissions
3. Review error logs
4. Test with sample player ID

### Issue: A/B test always returns same variant
**Solution:** This is expected - variant assignment is consistent per player

---

## Performance Tips

1. **Cache Tuning:** Adjust cache size and TTL based on your usage patterns
   ```python
   player_cache = PlayerDataCache(maxsize=512, ttl=600)  # 10 minute TTL
   ```

2. **Batch Message Size:** Increase for high-traffic scenarios
   ```python
   message_batcher = MessageBatcher(batch_size=20, flush_interval=0.2)
   ```

3. **Analytics Buffering:** Increase buffer for write-heavy workloads
   ```python
   tracker = AnalyticsTracker(db_connection)
   tracker._buffer_size = 500
   ```

---

## Support & Documentation

- **Full Documentation:** See `docs/archived/PHASES_5-7_IMPLEMENTATION_SUMMARY.md`
- **Production Checklist:** See `ws/deployment/production_checklist.md`
- **Legal Documents:**
  - Privacy: `ws/static/privacy.html`
  - Terms: `ws/static/terms.html`
  - Support: `ws/static/support.html`

---

**Version:** 1.0
**Last Updated:** November 12, 2025
**Status:** Production Ready (after testing)
