# 📋 Backup Operations Guide

## 🎯 Overview

This guide provides step-by-step instructions for performing backup operations with the BuzzTrail backup system, including manual backups, automated scheduling, and monitoring.

## 🚀 Quick Backup Operations

### 1. Manual Backup (Immediate)

```bash
# Trigger a full backup of all customers
curl -X POST http://localhost:3002/backup/trigger \
  -H "Content-Type: application/json" \
  -d '{
    "backupType": "full",
    "retentionDays": 30
  }'

# Response:
# {
#   "success": true,
#   "message": "Backup workflow triggered successfully", 
#   "backupType": "full",
#   "retentionDays": 30,
#   "timestamp": "2025-09-02T10:00:00.000Z"
# }
```

### 2. Manual Cleanup (Immediate)

```bash
# Clean up expired backups older than 30 days
curl -X POST http://localhost:3002/cleanup/trigger \
  -H "Content-Type: application/json" \
  -d '{
    "retentionDays": 30,
    "forceCleanup": false
  }'
```

### 3. Monitor via Workbench

1. Open http://localhost:3002/
2. View real-time workflow execution
3. Inspect step-by-step progress
4. Check logs and state data

## 📊 Comprehensive Backup Operations

### Step 1: Prepare Your Environment

```bash
# 1. Ensure Motia server is running
npx motia dev --port 3002

# 2. Verify database connectivity
sqlite3 backup-workflows/backup-data.db ".tables"
# Should show all 16+ tables including tavus_*, langfuse_*, backup_*

# 3. Check available disk space (backups can be large)
df -h .
```

### Step 2: Customer Management

#### Add New Customers

```typescript
// Example: Adding customers via database API
import { DatabaseManager } from '@buzztrail/accounts-backup';

const db = DatabaseManager.getInstance();

// Create a new customer
const customer = await db.createCustomer(
  'Acme Corporation',
  'vapi-org-12345' // Optional VAPI org ID
);

console.log('Customer created:', customer.customer_id);
```

#### List Existing Customers

```bash
# Via SQLite CLI
sqlite3 backup-data.db "SELECT customer_id, customer_name, created_at FROM customers WHERE is_active = TRUE;"

# Expected output:
# customer-uuid-1|Acme Corporation|2025-09-02T10:00:00.000Z
# customer-uuid-2|Beta Company|2025-09-02T09:00:00.000Z
```

### Step 3: Configure Service Accounts

#### Add Tavus Accounts

```typescript
// Add Tavus account for a customer
const tavusAccountId = await db.createTavusAccount(
  customer.customer_id,
  'production', // or 'testing'
  'tavus-account-id-123',
  'tavus-api-key-secret',
  'Production Tavus Account'
);
```

#### Add Langfuse Configuration

```typescript
// Langfuse configuration (stored as customer metadata or environment variables)
const langfuseConfig = {
  baseUrl: 'https://your-langfuse-instance.com',
  apiKey: 'lf_sk_...',
  projectId: 'project-123'
};
```

### Step 4: Backup Execution Options

#### Option A: Full Backup (Recommended for First Run)

```bash
# Full backup includes all data types
curl -X POST http://localhost:3002/backup/trigger \
  -H "Content-Type: application/json" \
  -d '{
    "backupType": "full",
    "retentionDays": 90
  }'

# This will backup:
# ✅ All customer data
# ✅ Tavus conversations, personas, replicas
# ✅ Langfuse traces, observations, datasets
# ✅ System configuration and metadata
```

#### Option B: Incremental Backup (Daily Use)

```bash
# Incremental backup includes only new/changed data
curl -X POST http://localhost:3002/backup/trigger \
  -H "Content-Type: application/json" \
  -d '{
    "backupType": "incremental", 
    "retentionDays": 30
  }'

# Faster execution, smaller files
# Recommended for automated daily backups
```

### Step 5: Monitor Backup Progress

#### Real-time Monitoring (Motia Workbench)

1. **Open Workbench**: http://localhost:3002/
2. **View Flow Diagram**: See backup workflow visualization
3. **Monitor Steps**: Watch each step execute in real-time:
   - `BackupInit`: Customer discovery and configuration ⏳
   - `BackupExecution`: Data collection and compression ⏳ 
   - `BackupFinish`: Report generation and completion ⏳
4. **Check Logs**: View detailed execution logs with timestamps
5. **Inspect State**: View data passed between workflow steps

#### Command-Line Monitoring

```bash
# Check backup job status
sqlite3 backup-data.db "
SELECT id, service_name, status, progress_percentage, 
       records_processed, started_at 
FROM export_jobs 
WHERE status IN ('running', 'pending') 
ORDER BY started_at DESC;
"

# Check recent backup completion
sqlite3 backup-data.db "
SELECT customer_id, service, backup_type, 
       file_size, created_at 
FROM backups 
ORDER BY created_at DESC 
LIMIT 10;
"
```

### Step 6: Backup Verification

#### Verify Backup Files

```bash
# Check backup file system structure
ls -la backup-workflows/backup-data/
# Should show:
# customers/
# ├── customer-uuid-1/
# │   ├── 2025-09-02T10-00-00-000Z/
# │   │   ├── tavus-data/
# │   │   ├── langfuse-data/
# │   │   └── backup-metadata.json
# temp/
# └── compressed-archives/

# Check compressed backup files
ls -lah backup-workflows/backup-data/temp/
# customer-uuid-1-full-2025-09-02T10-00-00-000Z.zip
# customer-uuid-2-incremental-2025-09-02T09-00-00-000Z.zip
```

#### Verify Database Records

```bash
# Check backup record integrity
sqlite3 backup-data.db "
SELECT COUNT(*) as backup_count,
       SUM(file_size) as total_size_bytes,
       AVG(file_size) as avg_size_bytes
FROM backups 
WHERE created_at > datetime('now', '-24 hours');
"

# Check for failed backups
sqlite3 backup-data.db "
SELECT customer_id, error_message, started_at 
FROM export_jobs 
WHERE status = 'failed' 
ORDER BY started_at DESC;
"
```

## ⚙️ Automated Backup Scheduling

### Setup Automated Daily Backups

```typescript
// Create a backup schedule for a customer
const schedule = await db.createBackupSchedule({
  customer_id: 'customer-uuid-123',
  service_name: 'unified', // Backs up both Tavus and Langfuse
  schedule_type: 'daily',
  schedule_config: {
    cron: '0 2 * * *', // Daily at 2 AM UTC
    timezone: 'UTC'
  },
  backup_type: 'incremental',
  retention_days: 30,
  is_active: true,
  next_run_at: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString()
});
```

### Setup Automated Weekly Full Backups

```typescript
const weeklySchedule = await db.createBackupSchedule({
  customer_id: 'customer-uuid-123',
  service_name: 'unified',
  schedule_type: 'weekly', 
  schedule_config: {
    cron: '0 1 * * 0', // Sundays at 1 AM UTC
    timezone: 'UTC'
  },
  backup_type: 'full',
  retention_days: 90,
  is_active: true
});
```

### Monitor Scheduled Backups

```bash
# Check active schedules
sqlite3 backup-data.db "
SELECT customer_id, service_name, schedule_type, 
       backup_type, next_run_at, is_active
FROM backup_schedules 
WHERE is_active = TRUE 
ORDER BY next_run_at;
"

# Check schedule execution history
sqlite3 backup-data.db "
SELECT bs.customer_id, bs.service_name, ej.status,
       ej.started_at, ej.completed_at
FROM backup_schedules bs
JOIN export_jobs ej ON bs.customer_id = ej.customer_id
WHERE ej.started_at > datetime('now', '-7 days')
ORDER BY ej.started_at DESC;
"
```

## 🧹 Cleanup Operations

### Step 1: Manual Cleanup

```bash
# Remove backups older than 30 days
curl -X POST http://localhost:3002/cleanup/trigger \
  -H "Content-Type: application/json" \
  -d '{
    "retentionDays": 30,
    "forceCleanup": false
  }'

# Force cleanup (ignore retention policies)
curl -X POST http://localhost:3002/cleanup/trigger \
  -H "Content-Type: application/json" \
  -d '{
    "retentionDays": 7,
    "forceCleanup": true
  }'
```

### Step 2: Configure Retention Policies

```typescript
// Set different retention policies per service/data type
await db.upsertDataRetentionPolicy({
  customer_id: 'customer-uuid-123',
  service_name: 'tavus',
  data_type: 'conversations',
  retention_days: 365, // Keep conversations for 1 year
  auto_cleanup: true,
  archive_before_delete: true
});

await db.upsertDataRetentionPolicy({
  customer_id: 'customer-uuid-123', 
  service_name: 'langfuse',
  data_type: 'traces',
  retention_days: 90, // Keep traces for 3 months
  auto_cleanup: true,
  archive_before_delete: false // Delete directly
});
```

### Step 3: Monitor Cleanup Results

```bash
# Check cleanup execution results
sqlite3 backup-data.db "
SELECT service_name, 
       SUM(records_processed) as total_cleaned,
       AVG(progress_percentage) as avg_progress
FROM export_jobs 
WHERE export_type = 'cleanup' 
  AND completed_at > datetime('now', '-24 hours')
GROUP BY service_name;
"
```

## 📊 Backup Monitoring and Reporting

### Daily Backup Report

```bash
# Generate daily backup summary
sqlite3 backup-data.db "
SELECT 
  DATE(created_at) as backup_date,
  COUNT(*) as backup_count,
  SUM(file_size) / 1024 / 1024 as total_mb,
  AVG(file_size) / 1024 as avg_kb
FROM backups 
WHERE created_at > datetime('now', '-7 days')
GROUP BY DATE(created_at)
ORDER BY backup_date DESC;
"
```

### Customer Backup Status

```bash
# Check backup status per customer
sqlite3 backup-data.db "
SELECT 
  c.customer_name,
  COUNT(b.backup_id) as backup_count,
  MAX(b.created_at) as last_backup,
  SUM(b.file_size) / 1024 / 1024 as total_mb
FROM customers c
LEFT JOIN backups b ON c.customer_id = b.customer_id
WHERE c.is_active = TRUE
GROUP BY c.customer_id, c.customer_name
ORDER BY last_backup DESC;
"
```

### Storage Usage Report

```bash
# Check storage usage and growth
du -sh backup-workflows/backup-data/
# Output: 2.1G  backup-workflows/backup-data/

# Breakdown by customer
du -sh backup-workflows/backup-data/customers/*/
# 450M  backup-workflows/backup-data/customers/customer-uuid-1/
# 320M  backup-workflows/backup-data/customers/customer-uuid-2/
```

## 🚨 Troubleshooting and Recovery

### Common Issues

#### Backup Failures

```bash
# Check failed backup jobs
sqlite3 backup-data.db "
SELECT id, customer_id, service_name, error_message, started_at
FROM export_jobs 
WHERE status = 'failed'
ORDER BY started_at DESC
LIMIT 10;
"

# Retry failed backup
curl -X POST http://localhost:3002/backup/trigger \
  -H "Content-Type: application/json" \
  -d '{"backupType": "full", "retentionDays": 30}'
```

#### Database Issues

```bash
# Check database integrity
sqlite3 backup-data.db "PRAGMA integrity_check;"
# Should return: ok

# Check foreign key constraints
sqlite3 backup-data.db "PRAGMA foreign_key_check;"
# Should return empty (no constraint violations)

# Vacuum database to reclaim space
sqlite3 backup-data.db "VACUUM;"
```

#### Storage Issues

```bash
# Check available disk space
df -h .
# Ensure sufficient space for backups

# Clean up temporary files
rm -rf backup-workflows/backup-data/temp/*.tmp

# Archive old backups
tar -czf old-backups-$(date +%Y%m%d).tar.gz backup-workflows/backup-data/customers/*/2024-*
```

### Recovery Procedures

#### Restore from Backup

```bash
# Extract backup archive
cd backup-workflows/backup-data/temp/
unzip customer-uuid-1-full-2025-09-02T10-00-00-000Z.zip -d restore/

# Check backup contents
ls -la restore/
# Should show: tavus-data/, langfuse-data/, metadata.json

# Import data back to database (custom script needed)
```

#### Database Recovery

```bash
# Backup current database
cp backup-data.db backup-data.db.backup

# Restore from earlier backup
cp backup-data.db.$(date -d "yesterday" +%Y%m%d) backup-data.db

# Re-run migrations if needed
cd libs/accounts-backup
npx ts-node src/test-migrations.ts
```

## 📋 Best Practices

### Backup Strategy

1. **Daily Incremental**: Automated daily incremental backups
2. **Weekly Full**: Automated weekly full backups  
3. **Monthly Archive**: Monthly archive to external storage
4. **Critical Events**: Manual backups before system changes

### Retention Policies

- **Conversations**: 365 days (critical customer data)
- **Traces/Observations**: 90 days (development/debugging data)
- **Media Assets**: 180 days (training materials)
- **System Logs**: 30 days (operational data)

### Monitoring

- **Daily**: Check backup completion status
- **Weekly**: Review storage usage and growth
- **Monthly**: Verify backup integrity and recovery procedures
- **Quarterly**: Test full disaster recovery process

Your backup operations are now fully configured and ready for production use! 🚀