# Dual Spotify API Credentials Setup

## Overview
The backend now supports dual Spotify API credentials to handle rate limiting. When the primary credentials hit rate limits (HTTP 429), the system automatically switches to fallback credentials.

## Environment Variables Required

### Primary Credentials (existing)
```bash
SPOTIFY_CLIENT_ID=your_primary_client_id
SPOTIFY_CLIENT_SECRET=your_primary_client_secret
```

### Fallback Credentials (new)
```bash
SPOTIFY_CLIENT_ID_FALLBACK=your_fallback_client_id
SPOTIFY_CLIENT_SECRET_FALLBACK=your_fallback_client_secret
```

## How to Set Up Fallback Credentials

1. **Create a second Spotify app** at https://developer.spotify.com/dashboard
   - Go to Spotify Developer Dashboard
   - Create New App
   - Fill in app details (name, description)
   - Note down the Client ID and Client Secret

2. **Add fallback credentials to your environment**:
   
   **For Docker (recommended):**
   Add to your `docker-compose.yml` or `.env` file:
   ```bash
   SPOTIFY_CLIENT_ID_FALLBACK=your_second_app_client_id
   SPOTIFY_CLIENT_SECRET_FALLBACK=your_second_app_client_secret
   ```

   **For local development:**
   Add to your shell profile or export directly:
   ```bash
   export SPOTIFY_CLIENT_ID_FALLBACK=your_second_app_client_id
   export SPOTIFY_CLIENT_SECRET_FALLBACK=your_second_app_client_secret
   ```

## How It Works

1. **Normal Operation**: Uses primary credentials (SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET)

2. **Rate Limit Detection**: When Spotify returns HTTP 429 (Too Many Requests), the system:
   - Automatically switches to fallback credentials
   - Logs the switch for monitoring
   - Continues serving requests without interruption

3. **Fallback Operation**: Uses secondary credentials (SPOTIFY_CLIENT_ID_FALLBACK, SPOTIFY_CLIENT_SECRET_FALLBACK)

4. **Recovery**: System can be soft-reset via `/api/soft-reset` endpoint to return to primary credentials

## Benefits

- **Zero Downtime**: Automatic failover when rate limits are hit
- **Double API Quota**: Effectively doubles your Spotify API request limit
- **Transparent**: Frontend experiences no interruption during credential switching
- **Recovery**: Soft reset capability to return to primary credentials when desired

## Testing

To test the fallover system:

1. **Start the backend** with both sets of credentials configured
2. **Monitor logs** for "Initializing Spotify service with dual credentials"
3. **Generate high API usage** to trigger rate limiting
4. **Watch for automatic failover** in logs: "Rate limit detected, switching to fallback credentials"
5. **Verify continued functionality** - Discover page should continue working

## Monitoring

The system logs important events:
- Credential initialization
- Rate limit detection
- Automatic failover
- Service resets

Watch the logs to understand when failovers occur and optimize your API usage patterns.
