# Trippy Beats Leaderboard Server

A lightweight, production-ready leaderboard server for the Trippy Beats music game.

## Features

- 🚀 **Fast & Lightweight** - Built with Express.js
- 🔒 **Secure** - Input validation, rate limiting, CORS protection
- 📊 **Complete API** - All leaderboard operations + statistics
- 🐳 **Docker Ready** - Easy deployment with Docker
- 🧪 **Tested** - Comprehensive test suite included
- 📁 **File-based Storage** - No database required
- ⚡ **Production Ready** - Error handling, logging, graceful shutdown

## Quick Start

### Prerequisites

- Node.js 16+ 
- npm or yarn

### Installation

```bash
# Install dependencies
npm install

# Start the server
npm start

# For development with auto-restart
npm run dev
```

### Test the Server

```bash
# Run comprehensive tests
npm test

# Manual health check
curl http://localhost:3000/api/health
```

## API Endpoints

### Core Endpoints

| Method | Endpoint | Description |
|--------|----------|-------------|
| `GET` | `/api/health` | Health check |
| `GET` | `/api/leaderboard` | Get all leaderboard data |
| `POST` | `/api/leaderboard` | Upload/update leaderboard |
| `GET` | `/api/player/:level/:name` | Get player's score for level |
| `GET` | `/api/level/:name` | Get leaderboard for specific level |
| `GET` | `/api/stats` | Get server statistics |

### Example Requests

```bash
# Get health status
curl http://localhost:3000/api/health

# Get all leaderboards
curl http://localhost:3000/api/leaderboard

# Get player score
curl http://localhost:3000/api/player/level1/PlayerName

# Upload leaderboard (example)
curl -X POST http://localhost:3000/api/leaderboard \
  -H "Content-Type: application/json" \
  -d '{
    "levels": [
      {
        "name": "level1",
        "scores": [
          {
            "player": "Player1",
            "score": 12345,
            "time": 120000,
            "highestLayer": "3/8",
            "highestCombo": 25
          }
        ]
      }
    ]
  }'
```

## Data Format

### Leaderboard Structure

```json
{
  "levels": [
    {
      "name": "level_name",
      "scores": [
        {
          "player": "player_name",
          "score": 12345,
          "time": 120000,
          "highestLayer": "3/8",
          "highestCombo": 25
        }
      ]
    }
  ],
  "metadata": {
    "created": "2025-01-01T00:00:00.000Z",
    "lastUpdated": "2025-01-01T00:00:00.000Z",
    "version": "1.0.0"
  }
}
```

## Configuration

Copy `config.example.js` to `config.js` and modify:

```javascript
module.exports = {
    port: 3000,
    cors: {
        allowedOrigins: '*' // or ['http://localhost:8080']
    },
    rateLimit: {
        max: 100 // requests per 15 minutes
    }
};
```

### Environment Variables

- `PORT` - Server port (default: 3000)
- `NODE_ENV` - Environment (development/production)
- `ALLOWED_ORIGINS` - CORS origins (comma-separated)
- `RATE_LIMIT_MAX` - Max requests per 15 minutes

## Deployment

### Option 1: Direct Node.js

```bash
# Production mode
NODE_ENV=production npm start

# With custom port
PORT=8080 npm start

# With PM2 (recommended for production)
npm install -g pm2
pm2 start server.js --name trippy-beats-server
```

### Option 2: Docker

```bash
# Build image
npm run docker:build

# Run container
npm run docker:run

# Or manually:
docker build -t trippy-beats-server .
docker run -p 3000:3000 -v $(pwd)/data:/app/data trippy-beats-server
```

### Option 3: Cloud Deployment

**Heroku:**
```bash
git init
git add .
git commit -m "Initial commit"
heroku create your-app-name
git push heroku main
```

**Railway/Render/DigitalOcean Apps:**
- Connect GitHub repository
- Set Node.js environment
- Deploy automatically

## File Structure

```
server/
├── server.js           # Main server file
├── test.js            # Test suite
├── package.json       # Dependencies
├── Dockerfile         # Docker configuration
├── config.example.js  # Configuration template
├── README.md          # This file
└── data/             # Data directory (auto-created)
    └── leaderboard.json
```

## Security Features

- **Rate Limiting** - Prevents abuse (100 requests/15 min per IP)
- **Input Validation** - Validates all incoming data
- **Input Sanitization** - Strips dangerous characters
- **CORS Protection** - Configurable origin restrictions
- **Helmet.js** - Security headers
- **Error Handling** - Prevents information leakage

## Monitoring & Logs

The server logs all requests and errors to console:

```
[2025-01-01T12:00:00.000Z] GET /api/health - 127.0.0.1
[2025-01-01T12:00:01.000Z] POST /api/leaderboard - 127.0.0.1
Served leaderboard data (1 levels)
Leaderboard updated successfully (1 levels)
```

## Development

### Adding New Endpoints

1. Add route in `server.js`:
```javascript
app.get('/api/new-endpoint', async (req, res) => {
    // Implementation
});
```

2. Add validation if needed
3. Update tests in `test.js`
4. Update this README

### Database Migration

To migrate from file storage to a database:

1. Replace `readLeaderboard()` and `writeLeaderboard()` functions
2. Add database connection configuration
3. Update Docker configuration if needed

## Troubleshooting

### Common Issues

**Port already in use:**
```bash
# Find process using port 3000
lsof -i :3000
# Kill it
kill -9 <PID>
```

**Permission denied (Docker):**
```bash
# Fix data directory permissions
chmod 755 data/
```

**CORS errors:**
- Set `ALLOWED_ORIGINS` environment variable
- Or modify cors configuration in server

### Health Check

The server includes a health check endpoint that reports:
- Server status
- Uptime
- Current timestamp
- Version info

## License

MIT License - see game's main LICENSE file.

## Support

For issues and questions:
1. Check the logs for error messages
2. Verify configuration settings
3. Test with the included test suite
4. Check network connectivity and firewall settings 