# Lilith iOS Application

A comprehensive iOS application built with React Native, featuring full offline support, biometric authentication, push notifications, and advanced audio capabilities.

## 🚀 Features

### Core Functionality
- **React Native Integration**: Cross-platform compatibility with native iOS enhancements
- **Offline-First Architecture**: Complete offline functionality with intelligent synchronization
- **Core Data Persistence**: Robust local data storage with automatic conflict resolution
- **Background Sync**: Seamless synchronization when connectivity is restored

### iOS-Specific Features
- **Biometric Authentication**: Face ID and Touch ID integration for secure access
- **Push Notifications**: Rich notification support with custom actions and categories
- **Background Audio**: Continuous playback of guided meditations and TTS content
- **Keychain Storage**: Secure storage of sensitive data and authentication tokens

## 📱 Architecture

### Project Structure
```
ios/
├── Lilith.xcodeproj/          # Xcode project configuration
├── Lilith/                    # Main application bundle
│   ├── AppDelegate.h/.m       # Application lifecycle management
│   ├── main.m                 # Application entry point
│   ├── Info.plist            # Application configuration
│   ├── LaunchScreen.storyboard # App launch screen
│   ├── Images.xcassets/       # App icons and images
│   ├── Managers/              # Native iOS managers
│   │   ├── LilithCoreDataManager.h/.m      # Core Data persistence
│   │   ├── LilithOfflineSyncManager.h/.m   # Background synchronization
│   │   ├── LilithBiometricManager.h/.m     # Biometric authentication
│   │   ├── LilithNotificationManager.h/.m  # Push notifications
│   │   └── LilithAudioManager.h/.m         # Audio playback and TTS
│   └── DataModel/             # Core Data model definition
│       └── LilithDataModel.xcdatamodeld/Contents
├── LilithTests/               # Unit and integration tests
├── Podfile                    # iOS dependencies
└── README.md                  # This documentation
```

### Core Components

#### LilithCoreDataManager
- **Purpose**: Manages Core Data operations and offline persistence
- **Features**:
  - Multi-context architecture (main + background)
  - Automatic migration support
  - Cache management and cleanup
  - Sync state tracking

#### LilithOfflineSyncManager
- **Purpose**: Handles background synchronization and offline queue management
- **Features**:
  - Network-aware sync scheduling
  - Conflict resolution algorithms
  - Retry mechanisms with exponential backoff
  - Background URL session support

#### LilithBiometricManager
- **Purpose**: Secure biometric authentication and keychain storage
- **Features**:
  - Face ID and Touch ID support
  - Secure value storage in keychain
  - Authentication timeout management
  - Fallback to passcode authentication

#### LilithNotificationManager
- **Purpose**: Rich notification system with intelligent scheduling
- **Features**:
  - Local and push notification handling
  - Custom notification categories and actions
  - Quiet hours and intelligent delivery
  - Badge management and background fetch

#### LilithAudioManager
- **Purpose**: Advanced audio playback and text-to-speech
- **Features**:
  - Background audio session management
  - Audio queue and playlist support
  - TTS integration with voice selection
  - Audio recording capabilities

## 🛠️ Development Setup

### Prerequisites
- Xcode 14.0+
- iOS Simulator 12.4+ or physical device
- CocoaPods 1.10+
- Node.js 16+

### Installation

1. **Install Dependencies**
   ```bash
   cd ios
   pod install
   ```

2. **Open Xcode Project**
   ```bash
   open Lilith.xcworkspace
   ```

3. **Configure Development Team**
   - Select the Lilith project
   - Set your development team in "Signing & Capabilities"
   - Update bundle identifier if needed

4. **Build and Run**
   - Select target device/simulator
   - Press Cmd+R or click Run button

### Development Workflow

#### Adding New Features
1. Create native manager in `Lilith/Managers/`
2. Implement header and implementation files
3. Add to AppDelegate integration
4. Create unit tests in `LilithTests/`
5. Update React Native bridge if needed

#### Testing
```bash
# Run unit tests
xcodebuild test -workspace Lilith.xcworkspace -scheme Lilith -destination 'platform=iOS Simulator,name=iPhone 14'

# Run from Xcode
# Product → Test (Cmd+U)
```

## 📊 Data Model

### Core Data Entities

#### Conversation
- `id`: String (Primary Key)
- `title`: String
- `persona`: String
- `createdAt`: Date
- `lastModified`: Date
- `needsSync`: Boolean
- `messages`: Relationship (one-to-many)

#### Message
- `id`: String (Primary Key)
- `content`: String
- `role`: String
- `createdAt`: Date
- `needsSync`: Boolean
- `conversation`: Relationship (many-to-one)

#### MeditationSession
- `id`: String (Primary Key)
- `type`: String
- `duration`: Integer
- `startTime`: Date
- `userId`: String
- `needsSync`: Boolean

#### UserPreferences
- `userId`: String (Primary Key)
- `preferencesData`: Binary (JSON)
- `lastModified`: Date

#### CacheEntity
- `key`: String (Primary Key)
- `data`: Binary
- `expiresAt`: Date
- `createdAt`: Date

## 🔧 Configuration

### Audio Session
```objc
// Background playback configuration
[session setCategory:AVAudioSessionCategoryPlayback
               mode:AVAudioSessionModeDefault
            options:AVAudioSessionCategoryOptionAllowBluetooth |
                    AVAudioSessionCategoryOptionAllowBluetoothA2DP |
                    AVAudioSessionCategoryOptionMixWithOthers
              error:&error];
```

### Notification Categories
- **MEDITATION_REMINDER**: Daily meditation prompts
- **DAILY_WISDOM**: Inspirational content with share/save actions
- **PROGRESS_UPDATE**: Achievement notifications
- **CHAT_RESPONSE**: AI mentor responses with reply actions

### Background Modes
The app supports the following background modes:
- **Audio**: Continuous media playback
- **Background Fetch**: Periodic data synchronization
- **Remote Notifications**: Silent push notifications
- **Background Processing**: Extended background tasks

## 🔒 Security Features

### Biometric Authentication
- **Face ID**: Secure authentication on supported devices
- **Touch ID**: Fingerprint authentication on older devices
- **Fallback**: Device passcode when biometrics fail
- **Timeout**: Configurable authentication timeout

### Keychain Storage
- **Secure**: Hardware-backed encryption
- **Persistent**: Survives app reinstalls
- **Shared**: Keychain access group configuration
- **Compliant**: Follows Apple security guidelines

## 📱 Platform Integration

### iOS Specific APIs
- **AVFoundation**: Audio playback and recording
- **Core Data**: Local persistence and relationships
- **UserNotifications**: Rich notification handling
- **LocalAuthentication**: Biometric authentication
- **CoreLocation**: Location-based preferences
- **Network Framework**: Connectivity monitoring

### React Native Bridge
Native managers are exposed to React Native through custom modules:
```javascript
import { NativeModules } from 'react-native';
const { LilithCoreDataManager, LilithAudioManager } = NativeModules;
```

## 🚨 Troubleshooting

### Common Issues

#### Build Errors
- **Missing Headers**: Ensure all `.h` files are properly imported
- **Signing Issues**: Verify development team and bundle identifier
- **Dependency Conflicts**: Run `pod update` to resolve version conflicts

#### Runtime Issues
- **Core Data Migration**: Check model version compatibility
- **Background Tasks**: Verify background modes are enabled
- **Audio Session**: Ensure proper category configuration

#### Testing Issues
- **Simulator Limitations**: Some features (biometrics) work only on devices
- **Network Conditions**: Test offline functionality with airplane mode
- **Memory Warnings**: Monitor for memory leaks in background tasks

### Debug Tools
- **Xcode Console**: Native log output
- **Instruments**: Performance and memory analysis
- **Core Data Editor**: Database inspection tools
- **Network Link Conditioner**: Poor connectivity testing

## 📚 API Reference

### Core Data Manager
```objc
// Create entity
NSManagedObject *conversation = [coreDataManager createEntity:@"Conversation"
                                                   inContext:context];

// Fetch entities
NSArray *results = [coreDataManager fetchEntities:@"Message"
                                          predicate:predicate
                                     sortDescriptors:descriptors
                                            inContext:context];

// Save context
[coreDataManager saveContext:context completion:^(NSError *error) {
    // Handle save result
}];
```

### Sync Manager
```objc
// Perform background sync
[syncManager performBackgroundSyncWithCompletion:^(BOOL success, NSError *error) {
    // Handle sync result
}];

// Cache data offline
[syncManager cacheConversation:conversationData withId:conversationId];
```

### Biometric Manager
```objc
// Authenticate with biometrics
[biometricManager authenticateWithReason:@"Access Lilith"
                                completion:^(BOOL success, NSError *error, NSString *reason) {
    // Handle authentication result
}];
```

## 🎯 Performance Optimization

### Memory Management
- Use background contexts for data operations
- Implement proper cleanup in dealloc methods
- Monitor for retain cycles with completion blocks

### Background Tasks
- Limit concurrent sync operations
- Implement intelligent retry mechanisms
- Use background URL sessions for large transfers

### Battery Life
- Optimize audio session management
- Use network reachability to avoid unnecessary requests
- Implement proper background task completion

## 📋 Testing Strategy

### Unit Tests
- Core Data operations (CRUD)
- Sync manager logic
- Biometric authentication flow
- Notification scheduling

### Integration Tests
- Offline-to-online workflows
- Background synchronization
- Audio session management
- Push notification handling

### UI Tests
- Authentication flows
- Audio playback controls
- Notification interactions
- Settings management

## 🔄 Version History

### v1.0.0 (Current)
- Complete iOS native implementation
- Full offline support with CoreData
- Biometric authentication integration
- Rich notification system
- Background audio playback
- Comprehensive test suite

---

**Development Team**: Lilith Mobile Team
**Last Updated**: October 11, 2025
**iOS Version**: 12.4+
**Xcode Version**: 14.0+