# Backend Unavailable - SDK Initialization Fix

## Problem Summary

The Onairos SDK initialization was failing when developers tried to initialize with their API keys. Through diagnostic testing, we discovered:

1. **Development API endpoint doesn't exist**: `dev-api.onairos.uk` - DNS lookup fails completely
2. **Production API endpoint is down**: `api.onairos.uk` returns 502 Bad Gateway - backend service not running

## Root Cause

The SDK's `initializeApiKey()` function was making HTTP requests to validate API keys against the backend API, but:
- The development endpoint (`https://dev-api.onairos.uk`) doesn't exist
- The production endpoint (`https://api.onairos.uk`) is returning 502 errors
- This caused initialization to fail even with valid API key formats

## Solutions Implemented

### 1. **Automatic Fallback to Offline Mode**

The SDK now automatically falls back to offline mode when the backend is unavailable (502, 503, 504 errors). In offline mode:
- API key format is validated locally (must be 32+ characters, start with `dev_`, `pk_`, or `ona_`)
- Initialization succeeds with limited permissions
- No backend validation is required

### 2. **Explicit Offline Mode**

You can now explicitly enable offline mode to skip backend validation entirely:

```dart
await initializeApiKey(
  apiKey: 'ona_VvoHNg1fdCCUa9eBy4Iz3IfvXdgLfMFI7TNcyHLDKEadPogkbjAeE2iDOs6M7Aey',
  environment: 'production',  // Use 'production' for all cases now
  enableLogging: true,
  offlineMode: true,  // Skip backend validation
);
```

### 3. **Unified Endpoint**

Both `development` and `production` environments now use the same endpoint (`https://api.onairos.uk`) since the development endpoint doesn't exist.

### 4. **Better Error Messages**

Error messages now include:
- Specific error codes (e.g., `SERVER_ERROR_502`, `OFFLINE_MODE_FALLBACK`)
- Clear descriptions of what went wrong
- Helpful context for debugging

## Recommended Usage

### For Testing/Development

**Option 1: Use Admin Key (No Validation)**
```dart
await initializeApiKey(
  apiKey: 'OnairosIsAUnicorn2025',  // Admin key bypasses validation
  environment: 'production',
  enableLogging: true,
);
```

**Option 2: Use Your API Key with Offline Mode**
```dart
await initializeApiKey(
  apiKey: 'ona_VvoHNg1fdCCUa9eBy4Iz3IfvXdgLfMFI7TNcyHLDKEadPogkbjAeE2iDOs6M7Aey',
  environment: 'production',
  enableLogging: true,
  offlineMode: true,  // Skip backend validation
);
```

### For Production (When Backend is Fixed)

```dart
await initializeApiKey(
  apiKey: 'ona_your_production_api_key_here',
  environment: 'production',
  enableLogging: false,  // Disable logging in production
);
```

The SDK will automatically fall back to offline mode if the backend is unavailable.

## API Key Requirements

For offline mode to work, your API key must:
1. Be at least 32 characters long
2. Start with one of: `dev_`, `pk_`, or `ona_`

Invalid keys will still fail even in offline mode.

## Example Implementation

Here's a complete example of how to initialize the SDK in your app:

```dart
import 'package:onairos/initialize_api_key.dart';

class AppConstants {
  static const String onairosApiKey = 'ona_VvoHNg1fdCCUa9eBy4Iz3IfvXdgLfMFI7TNcyHLDKEadPogkbjAeE2iDOs6M7Aey';
  static const String onairosEnvironment = 'production';
  static const bool testMode = true;
}

class OnairosManager {
  bool _isInitialized = false;
  
  Future<bool> initialize() async {
    try {
      // In test mode, you can use offline mode or admin key
      if (AppConstants.testMode) {
        await initializeApiKey(
          apiKey: AppConstants.onairosApiKey,
          environment: AppConstants.onairosEnvironment,
          enableLogging: true,
          offlineMode: true,  // Skip backend validation in test mode
        );
      } else {
        // In production, let it try backend validation with automatic fallback
        await initializeApiKey(
          apiKey: AppConstants.onairosApiKey,
          environment: AppConstants.onairosEnvironment,
          enableLogging: false,
        );
      }
      
      _isInitialized = true;
      debugPrint('✅ Onairos SDK initialized successfully');
      return true;
    } catch (error) {
      debugPrint('❌ Onairos SDK initialization failed: $error');
      _isInitialized = false;
      return false;
    }
  }
}
```

## What Changed in the Code

### 1. `api_key_validation_service.dart`
- Added `offlineMode` parameter to skip backend validation
- Added automatic fallback when backend returns 5xx errors
- Fixed endpoint configuration (dev and prod now use same URL)
- Better error detection and reporting

### 2. `initialize_api_key.dart`
- Added `offlineMode` parameter
- Improved documentation with examples
- Better logging messages

### 3. `onairos_config.dart`
- Added `offlineMode` field to configuration

### 4. `api_key_service.dart` and `onairos_service.dart`
- Propagated `offlineMode` parameter through the initialization chain
- Improved error messages and logging

## Testing

Run the diagnostic tool to check endpoint availability:

```bash
cd onairos
dart run test_endpoint_connectivity.dart
```

This will test both production and development endpoints and provide recommendations.

## When Will Backend Be Fixed?

Until the backend API is deployed and working:
- **Use offline mode** for development/testing
- **Use admin key** for internal testing
- The SDK will **automatically fall back** to offline mode if backend is unavailable

Once the backend is fixed, the SDK will automatically use full validation without any code changes needed.

## Support

If you continue to experience issues:
1. Ensure your API key format is correct (32+ chars, starts with `ona_`, `dev_`, or `pk_`)
2. Try using offline mode explicitly: `offlineMode: true`
3. Enable logging to see detailed error messages: `enableLogging: true`
4. Check the diagnostic output: `dart run test_endpoint_connectivity.dart`

## Summary

✅ **Immediate Fix**: SDK now works even when backend is unavailable
✅ **Automatic Fallback**: Detects 502/503 errors and uses offline mode
✅ **Explicit Control**: Can force offline mode with `offlineMode: true`
✅ **Better Errors**: Clear error messages with codes
✅ **No Breaking Changes**: Existing code continues to work

