# Offline Support Guide

Complete guide for implementing offline functionality in Lilith applications,
including content caching, sync strategies, and conflict resolution.

---

## Overview

Lilith supports full offline functionality allowing users to:

- Download meditations and courses for offline playback
- Continue conversations that sync when reconnected
- Track progress locally with eventual consistency
- Access cached content without network

---

## Architecture

### Offline Stack

```
┌─────────────────────────────────────────┐
│           Application Layer             │
├─────────────────────────────────────────┤
│         Sync Manager Service            │
│  ┌─────────┐ ┌─────────┐ ┌─────────┐   │
│  │ Content │ │Progress │ │  Chat   │   │
│  │  Cache  │ │  Sync   │ │  Queue  │   │
│  └─────────┘ └─────────┘ └─────────┘   │
├─────────────────────────────────────────┤
│         Local Storage Layer             │
│  ┌─────────┐ ┌─────────┐ ┌─────────┐   │
│  │ IndexDB │ │  SQLite │ │  Files  │   │
│  └─────────┘ └─────────┘ └─────────┘   │
└─────────────────────────────────────────┘
```

---

## Content Downloads

### Download Content for Offline

```http
POST /v1/offline/downloads
```

**Request Body:**

```json
{
  "content_id": "course_abc123",
  "content_type": "course",
  "quality": "high",
  "include_transcripts": true,
  "include_citations": true,
  "encryption_key": "user_device_key"
}
```

**Response:**

```json
{
  "download_id": "dl_xyz789",
  "content_id": "course_abc123",
  "status": "queued",
  "total_size_bytes": 250000000,
  "files": [
    { "file_id": "f1", "name": "lesson_01.opus", "size_bytes": 25000000 },
    { "file_id": "f2", "name": "lesson_02.opus", "size_bytes": 30000000 }
  ],
  "estimated_time_seconds": 120
}
```

### Get Download Status

```http
GET /v1/offline/downloads/{downloadId}
```

**Response:**

```json
{
  "download_id": "dl_xyz789",
  "status": "downloading",
  "progress": 0.45,
  "downloaded_bytes": 112500000,
  "total_bytes": 250000000,
  "current_file": "lesson_03.opus",
  "speed_bps": 5000000,
  "eta_seconds": 28
}
```

### List Downloads

```http
GET /v1/offline/downloads
```

### Cancel Download

```http
DELETE /v1/offline/downloads/{downloadId}
```

### Resume Download

```http
POST /v1/offline/downloads/{downloadId}/resume
```

---

## Offline Content Storage

### Storage Structure

```
/lilith-offline/
├── content/
│   ├── courses/
│   │   └── course_abc123/
│   │       ├── manifest.json
│   │       ├── lesson_01.opus.enc
│   │       ├── lesson_01.transcript.json
│   │       └── metadata.json
│   └── meditations/
│       └── med_xyz/
│           ├── audio.opus.enc
│           └── metadata.json
├── cache/
│   ├── personas.json
│   ├── daily_content.json
│   └── user_preferences.json
├── sync/
│   ├── pending_messages.json
│   ├── progress_queue.json
│   └── last_sync.json
└── keys/
    └── content_keys.enc
```

### Manifest Format

```json
{
  "content_id": "course_abc123",
  "version": 2,
  "downloaded_at": "2026-01-03T10:00:00Z",
  "expires_at": "2026-02-03T10:00:00Z",
  "encryption": {
    "algorithm": "AES-256-GCM",
    "key_id": "key_user_device"
  },
  "files": [
    {
      "file_id": "f1",
      "path": "lesson_01.opus.enc",
      "checksum": "sha256:abc123",
      "size_bytes": 25000000
    }
  ],
  "metadata": {
    "title": "Introduction to Meditation",
    "duration_ms": 3600000,
    "lesson_count": 10
  }
}
```

---

## Encryption

### Content Encryption

All offline content is encrypted using AES-256-GCM:

```javascript
// Encryption parameters
const encryptionConfig = {
  algorithm: 'AES-256-GCM',
  keyDerivation: 'PBKDF2',
  iterations: 100000,
  saltLength: 16,
  ivLength: 12,
  tagLength: 16,
};
```

### License Tokens

```http
POST /v1/offline/licenses
```

**Request Body:**

```json
{
  "content_id": "course_abc123",
  "device_id": "device_xyz",
  "offline_duration_days": 30
}
```

**Response:**

```json
{
  "license_id": "lic_abc",
  "content_key": "encrypted_key_data",
  "expires_at": "2026-02-03T10:00:00Z",
  "restrictions": {
    "max_plays": null,
    "device_bound": true
  }
}
```

### Validate License

```http
POST /v1/offline/licenses/validate
```

---

## Progress Sync

### Track Progress Locally

Store progress updates locally when offline:

```json
{
  "queue": [
    {
      "id": "prog_001",
      "content_id": "lesson_01",
      "position_ms": 125000,
      "completed": false,
      "timestamp": "2026-01-03T15:30:00Z",
      "synced": false
    }
  ]
}
```

### Sync Progress

```http
POST /v1/offline/sync/progress
```

**Request Body:**

```json
{
  "device_id": "device_xyz",
  "updates": [
    {
      "content_id": "lesson_01",
      "position_ms": 125000,
      "completed": false,
      "local_timestamp": "2026-01-03T15:30:00Z"
    },
    {
      "content_id": "lesson_02",
      "position_ms": 0,
      "completed": true,
      "local_timestamp": "2026-01-03T16:00:00Z"
    }
  ],
  "last_sync": "2026-01-02T10:00:00Z"
}
```

**Response:**

```json
{
  "synced": 2,
  "conflicts": [],
  "server_updates": [
    {
      "content_id": "lesson_03",
      "position_ms": 50000,
      "server_timestamp": "2026-01-03T12:00:00Z"
    }
  ],
  "sync_token": "sync_abc123"
}
```

### Conflict Resolution

When the same content has been updated on multiple devices:

```json
{
  "conflicts": [
    {
      "content_id": "lesson_01",
      "local": {
        "position_ms": 125000,
        "timestamp": "2026-01-03T15:30:00Z"
      },
      "server": {
        "position_ms": 200000,
        "timestamp": "2026-01-03T15:25:00Z"
      },
      "resolution": "last_write_wins",
      "resolved_value": {
        "position_ms": 125000
      }
    }
  ]
}
```

**Resolution Strategies:**

- `last_write_wins` - Most recent timestamp wins
- `furthest_progress` - Higher progress wins
- `manual` - User selects

---

## Chat Offline Queue

### Queue Messages Offline

```json
{
  "pending_messages": [
    {
      "local_id": "local_msg_001",
      "conversation_id": "conv_abc",
      "text": "What is mindfulness?",
      "created_at": "2026-01-03T15:30:00Z",
      "status": "pending"
    }
  ]
}
```

### Sync Chat Messages

```http
POST /v1/offline/sync/chat
```

**Request Body:**

```json
{
  "device_id": "device_xyz",
  "pending_messages": [
    {
      "local_id": "local_msg_001",
      "conversation_id": "conv_abc",
      "text": "What is mindfulness?",
      "created_at": "2026-01-03T15:30:00Z"
    }
  ],
  "last_sync": "2026-01-02T10:00:00Z"
}
```

**Response:**

```json
{
  "processed": [
    {
      "local_id": "local_msg_001",
      "server_id": "msg_xyz789",
      "response": {
        "message_id": "msg_response_001",
        "text": "Mindfulness is...",
        "citations": [...]
      }
    }
  ],
  "new_messages": [
    {
      "conversation_id": "conv_abc",
      "messages": [...]
    }
  ]
}
```

---

## Storage Management

### Get Storage Usage

```http
GET /v1/offline/storage
```

**Response:**

```json
{
  "total_bytes": 500000000,
  "used_bytes": 350000000,
  "available_bytes": 150000000,
  "by_type": {
    "courses": 200000000,
    "meditations": 100000000,
    "cache": 50000000
  },
  "items": [
    {
      "content_id": "course_abc",
      "size_bytes": 200000000,
      "downloaded_at": "2026-01-01T10:00:00Z",
      "last_accessed": "2026-01-03T15:00:00Z"
    }
  ]
}
```

### Delete Offline Content

```http
DELETE /v1/offline/content/{contentId}
```

### Clear Cache

```http
POST /v1/offline/cache/clear
```

**Request Body:**

```json
{
  "types": ["personas", "daily_content"],
  "older_than": "2026-01-01T00:00:00Z"
}
```

---

## Network Detection

### Check Connectivity

```javascript
// Web
const isOnline = navigator.onLine;

window.addEventListener('online', () => {
  syncManager.triggerSync();
});

window.addEventListener('offline', () => {
  offlineMode.enable();
});

// React Native
import NetInfo from '@react-native-community/netinfo';

NetInfo.addEventListener((state) => {
  if (state.isConnected) {
    syncManager.triggerSync();
  }
});
```

### Sync Trigger API

```http
POST /v1/offline/sync/trigger
```

---

## Background Sync

### Service Worker (Web)

```javascript
// Register sync
self.registration.sync.register('lilith-content-sync');

// Handle sync event
self.addEventListener('sync', (event) => {
  if (event.tag === 'lilith-content-sync') {
    event.waitUntil(syncOfflineData());
  }
});

async function syncOfflineData() {
  const pending = await getLocalPendingUpdates();
  await fetch('/v1/offline/sync', {
    method: 'POST',
    body: JSON.stringify(pending),
  });
}
```

### Background Fetch (Mobile)

```javascript
// React Native - Background Fetch
import BackgroundFetch from 'react-native-background-fetch';

BackgroundFetch.configure(
  {
    minimumFetchInterval: 15, // minutes
    stopOnTerminate: false,
    startOnBoot: true,
  },
  async (taskId) => {
    await syncOfflineContent();
    BackgroundFetch.finish(taskId);
  }
);
```

---

## Expiration & Refresh

### Content Expiration

Downloaded content expires based on license:

```json
{
  "expiration_policy": {
    "default_days": 30,
    "premium_days": 90,
    "purchased_days": 365,
    "warning_days_before": 7
  }
}
```

### Refresh Expired Content

```http
POST /v1/offline/content/{contentId}/refresh
```

### Check Expiration

```http
GET /v1/offline/content/expiring
```

**Response:**

```json
{
  "expiring_soon": [
    {
      "content_id": "course_abc",
      "expires_at": "2026-01-10T00:00:00Z",
      "days_remaining": 7
    }
  ],
  "expired": [
    {
      "content_id": "med_old",
      "expired_at": "2026-01-01T00:00:00Z"
    }
  ]
}
```

---

## Implementation Examples

### TypeScript SDK

```typescript
import { LilithClient, OfflineManager } from '@lilith/sdk-ts';

const client = new LilithClient({ apiKey: 'your-key' });
const offline = new OfflineManager(client);

// Download course for offline
await offline.download({
  contentId: 'course_abc123',
  quality: 'high',
  onProgress: (progress) => console.log(`${progress * 100}%`),
});

// Check if content available offline
const isAvailable = await offline.isAvailable('course_abc123');

// Play offline content
const audioUrl = await offline.getLocalUrl('course_abc123', 'lesson_01');

// Sync when online
await offline.sync();
```

### React Native

```typescript
import { useOffline } from '@lilith/mobile-sdk';

function MeditationScreen() {
  const { isOffline, downloadContent, getOfflineContent, syncProgress } =
    useOffline();

  const handleDownload = async () => {
    await downloadContent('meditation_xyz', {
      quality: 'high',
      onProgress: setProgress,
    });
  };

  useEffect(() => {
    if (!isOffline) {
      syncProgress();
    }
  }, [isOffline]);
}
```

---

## Error Handling

### Error Codes

| Code                        | Description               |
| --------------------------- | ------------------------- |
| `offline.storage_full`      | Device storage full       |
| `offline.content_expired`   | License expired           |
| `offline.sync_conflict`     | Conflict during sync      |
| `offline.download_failed`   | Download interrupted      |
| `offline.encryption_failed` | Decryption error          |
| `offline.invalid_license`   | License validation failed |

### Retry Strategy

```javascript
const retryConfig = {
  maxRetries: 3,
  initialDelay: 1000,
  maxDelay: 30000,
  backoffFactor: 2,
};
```

---

## Best Practices

1. **Pre-download popular content** during onboarding
2. **Respect storage limits** - prompt users when low
3. **Prioritize sync** - progress > messages > content
4. **Handle conflicts gracefully** - prefer user's latest action
5. **Background sync** - sync opportunistically when online
6. **Cache wisely** - personas and preferences first
7. **Encrypt everything** - content and user data
8. **Clear expired content** automatically

---

## Related Documentation

- [Offline Service README](/services/offline/README.md)
- [Progress Sync Service](/services/progress-sync/README.md)
- [Content Encryption Guide](/docs/security/content-encryption.md)
- [Mobile SDK Documentation](/sdk/mobile/README.md)
