# Crash Game - Full System Integration Guide

## Overview

The Crash Game system is now fully integrated with both Flutter frontend and Go backend. This guide explains how to deploy and run the complete system.

## System Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                   Flutter Frontend (Port: 5000)             │
│  ┌────────────────────────────────────────────────────────┐ │
│  │  Aviator Game Screen                                   │ │
│  │  - Places bets via REST API                            │ │
│  │  - Listens to WebSocket for multiplier updates         │ │
│  │  - Shows real-time animations                          │ │
│  └────────────────────────────────────────────────────────┘ │
└──────────────┬──────────────────────────────────────────────┘
               │
        HTTP + WebSocket
               │
┌──────────────┴──────────────────────────────────────────────┐
│                Go Backend (Port: 8888)                      │
│  ┌───────────────────┐  ┌──────────────────────────────┐   │
│  │ REST API Layer    │  │ WebSocket Handler            │   │
│  │ - Round Start     │  │ - Broadcast Multiplier       │   │
│  │ - Place Bet       │  │ - Broadcast Crash Events     │   │
│  │ - Cashout         │  │ - Player Connections         │   │
│  │ - Bet History     │  └──────────────────────────────┘   │
│  └────────┬──────────┘                                      │
│           │                                                  │
│  ┌─────────┴─────────────────────────────────────────────┐  │
│  │ Business Logic Layer (Services)                       │  │
│  │ - CrashGameService (game mechanics)                   │  │
│  │ - WalletService (balance management)                  │  │
│  └─────────┬───────────────────────────────────────────┘  │
│           │                                                  │
│  ┌─────────┴──────────────────────────────────────────────┐ │
│  │ Data Layer (Repositories + ORM)                        │  │
│  │ - GameRepository (GORM)                                │  │
│  │ - BetRepository (GORM)                                 │  │
│  │ - SQLite / PostgreSQL Database                         │  │
│  └──────────────────────────────────────────────────────┘  │
└──────────────────────────────────────────────────────────────┘
```

## Prerequisites

### Backend Requirements
- Go 1.18+
- SQLite (included, or PostgreSQL for production)
- Port 8888 available

### Frontend Requirements
- Flutter 3.0+
- Dart 3.0+
- Port 5000+ available (for web/desktop)

## Backend Setup & Run

### Step 1: Prepare Backend

```bash
# Navigate to project root
cd "d:\flutter project\avi"

# Download Go dependencies
go mod download

# Verify dependencies
go mod verify
```

### Step 2: Run Backend Server

```bash
# Run the server
go run cmd/server/main.go

# Expected output:
# [GIN-debug] Starting server on :8888
# [GIN-debug] Router setup completed
```

### Step 3: Verify Backend Health

```bash
# In another terminal
curl http://localhost:8888/health

# Expected response:
# {"status":"ok","time":"2024-04-08T10:00:00Z"}
```

## Frontend Setup & Run

### Step 1: Get Dependencies

```bash
# Get all Flutter packages
flutter pub get

# Build code generators (if needed)
flutter pub run build_runner build
```

### Step 2: Update API Configuration (if needed)

If your backend is not on `localhost:8888`, update:
- [BackendApiService.baseUrl](lib/data/services/backend_api_service.dart#L5)
- [WebSocket URL](lib/data/providers/websocket_provider.dart#L71)

```dart
// Example for remote server
static const String baseUrl = 'http://your-server.com:8888/api/v1/game';
//                           'ws://your-server.com:8888/api/v1/game/ws';
```

### Step 3: Run Flutter App

```bash
# Run on Windows
flutter run -d windows

# Run on macOS
flutter run -d macos

# Run on iOS (requires Xcode)
flutter run -d ios

# Run on Android device/emulator
flutter run -d android

# Run on web (requires Chrome)
flutter run -d chrome
```

## Testing the System

### Manual Test Flow

1. **Start Backend** (Terminal 1)
   ```bash
   go run cmd/server/main.go
   ```

2. **Start Frontend** (Terminal 2)
   ```bash
   flutter run -d windows
   ```

3. **Test in App**
   - Navigate to Aviator Game screen
   - Observe green dot (WebSocket connected) in top-right
   - Click "🔄 New Round" to start
   - Enter bet amount (e.g., 100)
   - Enter auto-cashout multiplier (e.g., 2.5)
   - Click "🚀 Place Bet"
   - Watch multiplier increase in real-time
   - Either cash out manually or wait for auto-cashout
   - Verify payout amount

### Test with cURL (Backend Only)

```bash
# 1. Start a round
curl -X POST http://localhost:8888/api/v1/game/round/start \
  -H "X-User-ID: testuser123" \
  -H "Content-Type: application/json"

# Response:
# {
#   "id": "round_abc123",
#   "status": "running",
#   "crash_time_ms": 3200,
#   "crash_multiplier": 4.5,
#   "started_at": "2024-04-08T10:00:00Z"
# }

# 2. Place a bet
curl -X POST http://localhost:8888/api/v1/game/bet \
  -H "X-User-ID: testuser123" \
  -H "Content-Type: application/json" \
  -d '{
    "round_id": "round_abc123",
    "amount": 100.0,
    "auto_cashout_multiplier": 2.5
  }'

# 3. Check bet history
curl http://localhost:8888/api/v1/game/bets \
  -H "X-User-ID: testuser123"
```

## Production Deployment

### Pre-Production Checklist

- [ ] **Authentication**: Replace `X-User-ID` with JWT/OAuth
- [ ] **Database**: Migrate from SQLite to PostgreSQL
- [ ] **HTTPS/WSS**: Enable SSL/TLS certificates
- [ ] **Environment Variables**: Use .env files for config
- [ ] **Rate Limiting**: Add rate limiting middleware
- [ ] **Logging**: Configure structured logging (JSON)
- [ ] **Monitoring**: Setup error tracking (Sentry, etc.)
- [ ] **Load Testing**: Verify 100+ concurrent players
- [ ] **Security**: Run security audit

### Docker Deployment

**Backend Dockerfile**:
```dockerfile
# backend/Dockerfile
FROM golang:1.21-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN go build -o server cmd/server/main.go

FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /app/server .
EXPOSE 8888
CMD ["./server"]
```

**Frontend Dockerfile**:
```dockerfile
# frontend/Dockerfile
FROM node:18 AS builder
WORKDIR /app
RUN npm install -g flutter
COPY . .
RUN flutter pub get
RUN flutter build web

FROM nginx:alpine
COPY --from=builder /app/build/web /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
```

**Docker Compose**:
```yaml
version: '3.8'

services:
  backend:
    build: ./backend
    ports:
      - "8888:8888"
    environment:
      - DB_HOST=postgres
      - DB_PORT=5432
      - DB_NAME=avi_crash
      - DB_USER=postgres
      - DB_PASSWORD=secure_password
    depends_on:
      - postgres

  frontend:
    build: ./frontend
    ports:
      - "80:80"
    depends_on:
      - backend

  postgres:
    image: postgres:15-alpine
    environment:
      POSTGRES_DB: avi_crash
      POSTGRES_PASSWORD: secure_password
    volumes:
      - postgres_data:/var/lib/postgresql/data

volumes:
  postgres_data:
```

### Environment Configuration

Create `.env` file:
```env
# Backend Configuration
API_PORT=8888
API_HOST=0.0.0.0

# Database (switch from SQLite to PostgreSQL for production)
DB_TYPE=postgres
DB_HOST=localhost
DB_PORT=5432
DB_NAME=avi_crash
DB_USER=postgres
DB_PASSWORD=your_secure_password

# Authentication
JWT_SECRET=your_super_secret_jwt_key
JWT_EXPIRY=24h

# Game Configuration
GAME_DURATION_MS=7000
MAX_MULTIPLIER=7.0
MIN_CRASH_MS=500
MAX_CRASH_MS=6800

# Logging
LOG_LEVEL=info
LOG_FORMAT=json
```

### Database Migration for Production

```go
// Switch database connection in cmd/server/main.go
func initDatabase() (*gorm.DB, error) {
    // PostgreSQL connection
    dsn := fmt.Sprintf(
        "host=%s port=%s user=%s password=%s dbname=%s sslmode=disable",
        os.Getenv("DB_HOST"),
        os.Getenv("DB_PORT"),
        os.Getenv("DB_USER"),
        os.Getenv("DB_PASSWORD"),
        os.Getenv("DB_NAME"),
    )
    
    db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{...})
    // ... rest of config
}
```

## Monitoring & Debugging

### Backend Logs

```bash
# View all logs
tail -f server.log

# View specific error
grep "error" server.log

# Monitor WebSocket connections
grep "WebSocket" server.log | tail -20
```

### Frontend Debugging

```dart
// Enable all logs in main.dart
void main() {
  // Set Flutter logging
  Logger.root.level = Level.ALL;
  Logger.root.onRecord.listen((record) {
    print('${record.level.name}: ${record.message}');
  });
  
  runApp(const MyApp());
}
```

### Check Database

```bash
# SQLite (development)
sqlite3 avi.db ".schema"
sqlite3 avi.db "SELECT COUNT(*) FROM game_rounds;"

# PostgreSQL (production)
psql -h localhost -U postgres -d avi_crash
# Then query: SELECT * FROM game_rounds ORDER BY started_at DESC LIMIT 10;
```

## Performance Optimization

### Backend Optimization
- Connection pooling (already configured in GORM)
- Database indexes (6 indexes configured)
- Query caching for frequent lookups
- Async broadcasting to WebSocket clients

### Frontend Optimization
- Riverpod caching automatically enabled
- AnimationController for smooth 50fps updates
- WebSocket keep-alive heartbeat (54s)
- Lazy loading of bet history

### Load Testing

```bash
# Install Apache Bench
apt-get install apache2-utils  # Linux
# or brew install httpd         # macOS

# Test backend API (100 requests, 10 concurrent)
ab -n 100 -c 10 \
  -H "X-User-ID: user123" \
  http://localhost:8888/api/v1/game/round/start

# WebSocket load test
npm install -g wscat
for i in {1..50}; do
  wscat -c "ws://localhost:8888/api/v1/game/ws" \
    --header "X-User-ID: user_$i" &
done
```

## Troubleshooting

### Backend Won't Start

```bash
# Port already in use
netstat -ano | findstr :8888  # Windows
lsof -i :8888                 # macOS/Linux

# Solution: Kill process or use different port
taskkill /PID <PID> /F  # Windows
kill -9 <PID>           # macOS/Linux
```

### WebSocket Connection Fails

```bash
# Check connectivity
curl -i -N -H "Connection: Upgrade" \
  -H "Upgrade: websocket" \
  http://localhost:8888/api/v1/game/ws

# Check firewall
ufw allow 8888  # Ubuntu
sudo pfctl -f /etc/pf.conf  # macOS
```

### Database Errors

```bash
# Check database connection
curl -X POST http://localhost:8888/api/v1/game/round/start \
  -H "X-User-ID: test" -v

# Watch server logs
go run cmd/server/main.go 2>&1 | grep -i "database\|error"
```

## Daily Operations

### Check Server Health
```bash
curl http://localhost:8888/health
```

### Monitor Active Games
```bash
# Count active rounds
curl http://localhost:8888/api/v1/game/rounds \
  -H "X-User-ID: admin"
```

### Backup Database

```bash
# SQLite backup
cp avi.db avi_$(date +%Y%m%d_%H%M%S).db

# PostgreSQL backup
pg_dump -U postgres avi_crash > backup_$(date +%Y%m%d).sql
```

### Restart Services

```bash
# Kill backend
pkill -f "go run cmd/server/main.go"

# Restart
go run cmd/server/main.go
```

## Support & Resources

- **Backend Issues**: Check [CRASH_GAME_BACKEND_INTEGRATION.md](CRASH_GAME_BACKEND_INTEGRATION.md)
- **Frontend Issues**: Check [CRASH_GAME_FRONTEND_GUIDE.md](CRASH_GAME_FRONTEND_GUIDE.md)
- **Game Logic**: See [CRASH_GAME_IMPLEMENTATION_SUMMARY.md](CRASH_GAME_IMPLEMENTATION_SUMMARY.md)
- **Architecture**: See [API_CODE_REVIEW_COMPLETE.md](API_CODE_REVIEW_COMPLETE.md)

## Next Steps

1. ✅ Run backend locally on port 8888
2. ✅ Run frontend locally on port 5000+
3. ✅ Test end-to-end game flow
4. ✅ Load test with multiple players
5. ✅ Deploy to staging environment
6. ✅ Setup monitoring and logging
7. ✅ Deploy to production
8. ✅ Monitor metrics and performance
