# Mobile Services Architecture

This directory contains the mobile platform services organized by domain. Each service follows a consistent pattern with separate interface, implementation, and test files.

## Service Organization

Services are organized into domain-specific directories. Most services follow the pattern:
- `ServiceName.ts` - Public interface (often re-export)
- `ServiceNameImpl.ts` - Implementation
- `__tests__/` - Unit tests

## Service Domains

### Audio & Voice
| Directory | Responsibility |
|-----------|---------------|
| `audio/` | Audio processing, playback, effects (binaural, spatial, etc.) |
| `voice/` | Speech recognition, voice synthesis, barge-in detection |
| `webrtc/` | Real-time voice/video communication |
| `bluetooth/` | Bluetooth audio device integration |

### User Experience
| Directory | Responsibility |
|-----------|---------------|
| `accessibility/` | Screen reader support, dynamic type, VoiceOver |
| `haptics/` | Tactile feedback for meditation and interaction |
| `notification/` | Local notification management |
| `notifications/` | Push notification handling |
| `deeplink/` | Deep link routing and handling |
| `share/` | Social sharing functionality |

### Data & Sync
| Directory | Responsibility |
|-----------|---------------|
| `sync/` | Real-time data synchronization |
| `progress/` | Cross-device progress tracking |
| `offline/` | Offline storage and bundle management |
| `storage/` | Local data persistence |
| `cache/` | Content caching and expiry |
| `data/` | Data access layer and transformations |
| `conflict/` | Conflict resolution for sync |

### Authentication & Security
| Directory | Responsibility |
|-----------|---------------|
| `auth/` | Authentication bridges, session management |
| `biometric/` | Biometric sensors (HRV, GSR, EEG), consciousness experiments, visual themes, spiritual practices (84 services - see note below) |
| `license/` | Content licensing and DRM |

### Meditation & Content
| Directory | Responsibility |
|-----------|---------------|
| `group/` | Group meditation sessions |
| `playlist/` | Meditation playlist management |
| `download/` | Content download management |
| `scheduler/` | Meditation session scheduling |
| `quiet/` | Quiet hours and do-not-disturb |

### Platform Integration
| Directory | Responsibility |
|-----------|---------------|
| `native/` | Native platform bridges (iOS/Android) |
| `device/` | Device capabilities and info |
| `handoff/` | Cross-device handoff (Continuity) |
| `quick-actions/` | Home screen quick actions |
| `ar/` | Augmented reality features |
| `metaverse/` | Virtual environment integration |

### Infrastructure
| Directory | Responsibility |
|-----------|---------------|
| `error/` | Error handling and reporting |
| `push/` | Push notification infrastructure |
| `payment/` | Payment processing integration |
| `user/` | User profile and preferences |
| `chat/` | Real-time chat synchronization |
| `lib/` | Shared utilities |

### Special Directories
| Directory | Purpose |
|-----------|---------|
| `__mocks__/` | Mock implementations for testing |
| `__tests__/` | Cross-cutting service tests |
| `integration/` | Service integration tests |

## Service Patterns

### Re-Export Architecture

Many services use a barrel export pattern where a thin top-level file re-exports from a subdirectory:

```
services/
├── DownloadManager.ts          # Re-export wrapper (4 lines)
└── download/
    ├── DownloadManager.ts      # Actual implementation
    ├── DownloadManagerImpl.ts  # Implementation details
    └── __tests__/              # Tests
```

**Rationale:**
1. **Clean imports** - Consumers use `import { DownloadManager } from 'services/DownloadManager'`
2. **Encapsulation** - Implementation details hidden in subdirectories
3. **Discoverability** - Top-level files serve as a service catalog
4. **Testing** - Subdirectories contain their own test suites
5. **Scalability** - Large services can split across multiple files

**Example re-export:**
```typescript
// services/DownloadManager.ts
export * from './download/DownloadManager';
export { default } from './download/DownloadManager';
```

This pattern is intentional and should be maintained for consistency.

### Export Patterns
Most services use default exports with class instances:
```typescript
// Pattern 1: Default export of class (most common - ~36 services)
export default class MyService {
  // implementation
}

// Pattern 2: Named class export (~10 services)
export class MyService {
  // implementation
}

// Pattern 3: Singleton with getInstance (rare - 2 services)
class MyService {
  private static instance: MyService;
  static getInstance(): MyService { ... }
}
export default MyService.getInstance();
```

### State Export/Import
Services requiring persistence implement:
```typescript
interface Persistable {
  exportState(): SerializedState;
  importState(state: SerializedState): void;
}
```

### Event-Driven Communication
Services communicate via event emitters for loose coupling:
```typescript
service.on('stateChanged', (newState) => { ... });
service.emit('event', data);
```

## Notes on Service Organization

### biometric/ Directory Contents

The `biometric/` directory contains 84 services spanning multiple domains that grew organically. While the name suggests only biometric-related functionality, it actually contains:

**Actual Biometric Services (14):**
- BiometricAuthService, HrvMonitoringService, GsrMonitoringService
- EegIntegrationService, EyeTrackingService, MovementTrackingService
- PostureMonitoringService, BreathPatternService, BreathworkProtocolService
- BodyTemperatureService, BiofieldMeasurementService, AuraImagingService
- ThermalModulationService, LightSoundMachineService

**Consciousness & Spiritual Practice Services (~30):**
- AstralProjectionTrainingService, LucidDreamInductionService, ConsciousnessTransferService
- EnochianMagicService, ChaosMagicToolkitService, InteractiveKabbalahService
- QuantumRngService, TelepathyExperimentService, RemoteViewingTrainingService
- RitualCeremonyService, SacredNumerologyService, OracleDivinationService, etc.

**Visual Theme Services (~20):**
- AnimeAestheticService, PsychedelicModeService, MinimalistZenModeService
- SacredGeometryInterfaceService, RetroPixelArtService, WatercolorMeditationService, etc.

**Community & Teaching Services (~10):**
- PersonalAiTeacherService, TeacherTrainingService, PhilosophyForumService
- SanghaCommunityService, MassMeditationEventService, WisdomSharingService, etc.

**Future Reorganization (deferred):**
A proper reorganization would create separate directories (`themes/`, `consciousness/`, `ritual/`, `community/`), but would require updating 100+ test imports. This is tracked as future work.

## Related Documentation

- `OfflineArchitecture.md` - Detailed offline sync architecture
- `/docs/service-interaction-patterns.md` - Service communication patterns
- `/docs/testing-strategy.md` - Testing guidelines for services
