# 🗄️ Database Management Guide

## 📊 Overview

This guide covers comprehensive database management for the BuzzTrail backup system, including schema management, migrations, performance optimization, and maintenance procedures.

## 🏗️ Database Architecture

### Schema Overview

The system uses **16 interconnected tables** organized into logical groups:

```
📊 Database Structure (SQLite)
├── Core Tables (4)
│   ├── customers                    # Customer management
│   ├── backups                      # Backup metadata
│   ├── customer_tavus_accounts      # Tavus credentials
│   └── tavus_sync_log              # Sync operations log
├── Tavus Extended (5)
│   ├── tavus_conversation_transcripts  # Full dialogue content
│   ├── tavus_persona_configurations    # AI behavior settings
│   ├── tavus_replica_training         # Training progress
│   ├── tavus_conversation_events      # System events
│   └── tavus_media_assets            # Media file management
├── Langfuse Integration (6) 
│   ├── langfuse_traces              # Core observability
│   ├── langfuse_observations        # LLM call details
│   ├── langfuse_sessions            # User sessions
│   ├── langfuse_scores              # Evaluation metrics
│   ├── langfuse_datasets            # Training datasets
│   └── langfuse_dataset_items       # Dataset entries
├── Backup Management (5)
│   ├── backup_schedules             # Automated scheduling
│   ├── export_jobs                  # Job tracking
│   ├── data_retention_policies      # Retention rules
│   ├── service_api_usage           # API rate limiting
│   └── backup_job_dependencies     # Workflow deps
└── System Tables (1)
    └── migrations                   # Schema versioning
```

## 🔧 Migration Management

### Check Migration Status

```typescript
// Via TypeScript API
import { DatabaseManager } from '@buzztrail/accounts-backup';

const db = DatabaseManager.getInstance();
const status = await db.getMigrationStatus();
console.log(status);

// Output:
// [
//   { version: '001', name: 'Add Tavus Extended Schema', executed: true },
//   { version: '002', name: 'Add Langfuse Schema', executed: true },
//   { version: '003', name: 'Add Backup Management Schema', executed: true },
//   { version: '004', name: 'Add Performance Indexes', executed: true }
// ]
```

```bash
# Via SQLite CLI
sqlite3 backup-data.db "SELECT * FROM migrations ORDER BY version;"

# Expected output:
# 001|Add Tavus Extended Schema|2025-09-02T10:00:00.000Z
# 002|Add Langfuse Schema|2025-09-02T10:01:00.000Z  
# 003|Add Backup Management Schema|2025-09-02T10:02:00.000Z
# 004|Add Performance Indexes|2025-09-02T10:03:00.000Z
```

### Run Migrations

```typescript
// Automatic migration on startup
const db = DatabaseManager.getInstance(); // Runs migrations automatically

// Manual migration execution
await db.runMigrations();
console.log('✅ All migrations completed');
```

### Rollback Migrations (Emergency)

```typescript
// Rollback specific migration
await db.rollbackMigration('004'); // Remove performance indexes
console.log('✅ Migration 004 rolled back');

// Check status after rollback
const status = await db.getMigrationStatus();
// version '004' will show executed: false
```

### Add New Migrations

```typescript
// Create new migration file: libs/accounts-backup/src/migrations/migrations/005_your_changes.ts
import Database from 'better-sqlite3';
import { Migration } from '../index';

export const migration: Migration = {
  version: '005',
  name: 'Add Your New Feature',
  
  up: (db: Database.Database) => {
    console.log('📋 Creating new tables...');
    
    db.exec(`
      CREATE TABLE IF NOT EXISTS your_new_table (
        id TEXT PRIMARY KEY,
        customer_id TEXT NOT NULL,
        data TEXT,
        created_at TEXT NOT NULL DEFAULT (datetime('now')),
        FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
      )
    `);
    
    console.log('✅ New tables created successfully');
  },

  down: (db: Database.Database) => {
    console.log('🔄 Rolling back new tables...');
    db.exec('DROP TABLE IF EXISTS your_new_table');
    console.log('✅ Tables rolled back');
  }
};

// Update migration manager index.ts to include new migration
```

## 📈 Performance Management

### Query Performance Analysis

```bash
# Enable query timing
sqlite3 backup-data.db
.timer on

# Analyze slow queries
EXPLAIN QUERY PLAN SELECT * FROM langfuse_traces WHERE customer_id = 'customer-123';

# Check index usage
SELECT name, sql FROM sqlite_master WHERE type='index' AND tbl_name='langfuse_traces';

# Performance benchmark
.timer on
SELECT COUNT(*) FROM langfuse_observations WHERE trace_id IN (
  SELECT id FROM langfuse_traces WHERE customer_id = 'customer-123'
);
```

### Index Management

```sql
-- Check existing indexes
SELECT name, tbl_name, sql FROM sqlite_master 
WHERE type='index' AND name NOT LIKE 'sqlite_%'
ORDER BY tbl_name, name;

-- Create custom indexes for your queries
CREATE INDEX IF NOT EXISTS idx_custom_query 
ON tavus_conversation_transcripts(customer_id, timestamp, role);

-- Drop unused indexes
DROP INDEX IF EXISTS idx_old_unused_index;

-- Analyze index effectiveness
ANALYZE;
```

### Database Optimization

```bash
# Database maintenance commands
sqlite3 backup-data.db

# Reclaim free space
VACUUM;

# Update query planner statistics
ANALYZE;

# Check database size and page usage
SELECT page_count * page_size as size FROM pragma_page_count(), pragma_page_size();

# Check fragmentation
PRAGMA freelist_count;

# Auto-vacuum settings (run once)
PRAGMA auto_vacuum = INCREMENTAL;
```

## 🔍 Data Management Operations

### Customer Management

```typescript
// Create new customer
const customer = await db.createCustomer(
  'New Company Inc.',
  'vapi-org-456'
);

// Get customer with related data
const customerData = await db.getCustomer(customer.customer_id);
const tavusAccounts = await db.getTavusAccounts(customer.customer_id);
const backups = await db.getBackupsForCustomer(customer.customer_id);

// Update customer (example - you may need to add this method)
// await db.updateCustomer(customer.customer_id, { customer_name: 'Updated Name' });
```

### Tavus Data Operations

```typescript
// Store conversation transcripts
await db.createConversationTranscript({
  conversation_id: 'conv-789',
  customer_id: customer.customer_id,
  role: 'assistant',
  content: 'Thank you for your question. I can help with that.',
  timestamp: new Date().toISOString(),
  metadata: {
    confidence_score: 0.95,
    response_time_ms: 1200,
    model_version: 'gpt-4'
  }
});

// Get conversation history
const transcripts = await db.getConversationTranscripts('conv-789');
console.log(`Found ${transcripts.length} messages in conversation`);

// Update persona configuration
await db.upsertPersonaConfiguration({
  persona_id: 'persona-456',
  customer_id: customer.customer_id,
  llm_model: 'gpt-4-turbo',
  personality_prompt: 'You are a professional customer service representative.',
  behavior_settings: {
    tone: 'professional',
    verbosity: 'concise',
    empathy_level: 'high'
  }
});

// Track replica training
await db.createReplicaTraining({
  replica_id: 'replica-789',
  customer_id: customer.customer_id,
  training_status: 'in_progress',
  progress_percentage: 45,
  training_duration_ms: 1800000, // 30 minutes
  source_materials: {
    video_urls: ['https://example.com/training1.mp4'],
    audio_samples: 15,
    total_duration_minutes: 120
  },
  started_at: new Date().toISOString()
});

// Update training progress
await db.updateReplicaTrainingProgress('replica-789', 85, 'completed');
```

### Langfuse Data Operations

```typescript
// Store trace data
const trace = await db.createTrace({
  customer_id: customer.customer_id,
  project_id: 'proj-123',
  name: 'Customer Support Chat',
  user_id: 'user-456',
  metadata: {
    session_type: 'support',
    priority: 'high',
    category: 'billing'
  },
  input: {
    user_message: 'I need help with my billing',
    context: { account_type: 'premium', last_payment: '2025-08-15' }
  },
  output: {
    assistant_response: 'I\'ll help you with your billing question.',
    action_taken: 'escalate_to_billing',
    resolution_time_minutes: 5
  },
  start_time: new Date().toISOString(),
  duration_ms: 4500,
  status: 'success'
});

// Store LLM call details
await db.createObservation({
  trace_id: trace.id,
  customer_id: customer.customer_id,
  type: 'llm',
  name: 'GPT-4 Classification',
  model: 'gpt-4',
  input: {
    system_prompt: 'Classify this customer inquiry...',
    user_message: 'I need help with my billing'
  },
  output: {
    classification: 'billing_inquiry',
    confidence: 0.92,
    suggested_actions: ['check_account', 'review_charges']
  },
  usage: {
    input_tokens: 45,
    output_tokens: 28,
    total_cost: 0.0023
  },
  start_time: new Date().toISOString(),
  level: 'DEFAULT'
});

// Query traces for analysis
const recentTraces = await db.getTracesByCustomer(customer.customer_id, 50);
console.log(`Found ${recentTraces.length} recent traces`);
```

### Backup Job Management

```typescript
// Create backup schedule
const schedule = await db.createBackupSchedule({
  customer_id: customer.customer_id,
  service_name: 'tavus',
  schedule_type: 'daily',
  schedule_config: {
    cron: '0 3 * * *', // 3 AM daily
    timezone: 'America/New_York'
  },
  backup_type: 'incremental',
  retention_days: 60,
  is_active: true,
  next_run_at: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString()
});

// Create and track export job
const job = await db.createExportJob({
  customer_id: customer.customer_id,
  service_name: 'langfuse',
  export_type: 'backup',
  status: 'pending',
  total_records: 5000,
  started_at: new Date().toISOString(),
  metadata: {
    backup_type: 'full',
    include_media: true,
    compression: 'gzip'
  }
});

// Update job progress (simulate long-running job)
await db.updateExportJobProgress(job.id, 25, 1250);
await db.updateExportJobProgress(job.id, 50, 2500);
await db.updateExportJobProgress(job.id, 75, 3750);

// Complete the job
await db.completeExportJob(job.id, 'completed');
```

## 📊 Monitoring and Analytics

### Database Health Checks

```sql
-- Overall database statistics
SELECT 
  (SELECT COUNT(*) FROM customers) as total_customers,
  (SELECT COUNT(*) FROM backups) as total_backups,
  (SELECT COUNT(*) FROM tavus_conversation_transcripts) as total_conversations,
  (SELECT COUNT(*) FROM langfuse_traces) as total_traces,
  (SELECT COUNT(*) FROM export_jobs WHERE status = 'running') as active_jobs;

-- Storage usage by table
SELECT 
  name as table_name,
  COUNT(*) as row_count
FROM sqlite_master 
WHERE type = 'table' AND name NOT LIKE 'sqlite_%'
GROUP BY name
ORDER BY row_count DESC;

-- Recent activity summary
SELECT 
  DATE(created_at) as date,
  COUNT(*) as backup_count,
  SUM(file_size) / 1024 / 1024 as total_mb
FROM backups 
WHERE created_at > datetime('now', '-30 days')
GROUP BY DATE(created_at)
ORDER BY date DESC;
```

### Performance Monitoring

```sql
-- Slow queries identification (enable with .timer on)
-- Run your typical queries and measure execution time

-- Index usage analysis
EXPLAIN QUERY PLAN 
SELECT t.customer_id, COUNT(o.id) as observation_count
FROM langfuse_traces t
LEFT JOIN langfuse_observations o ON t.id = o.trace_id
WHERE t.customer_id = 'customer-123'
GROUP BY t.customer_id;

-- Database size trends
SELECT 
  datetime('now') as check_time,
  page_count * page_size / 1024 / 1024 as size_mb,
  freelist_count as free_pages
FROM pragma_page_count(), pragma_page_size(), pragma_freelist_count();
```

### Data Quality Checks

```sql
-- Orphaned records (foreign key violations)
SELECT 'orphaned_transcripts' as issue, COUNT(*) as count
FROM tavus_conversation_transcripts t
LEFT JOIN customers c ON t.customer_id = c.customer_id
WHERE c.customer_id IS NULL

UNION ALL

SELECT 'orphaned_traces' as issue, COUNT(*) as count  
FROM langfuse_traces t
LEFT JOIN customers c ON t.customer_id = c.customer_id
WHERE c.customer_id IS NULL

UNION ALL

SELECT 'failed_jobs' as issue, COUNT(*) as count
FROM export_jobs
WHERE status = 'failed' AND created_at > datetime('now', '-7 days');

-- Data consistency checks
SELECT 
  'backup_file_mismatch' as issue,
  COUNT(*) as count
FROM backups b
WHERE NOT EXISTS (
  SELECT 1 FROM export_jobs ej 
  WHERE ej.customer_id = b.customer_id 
  AND ej.status = 'completed'
  AND ej.completed_at = b.created_at
);
```

## 🔧 Maintenance Procedures

### Daily Maintenance

```bash
#!/bin/bash
# daily-maintenance.sh

echo "🔧 Starting daily database maintenance..."

# 1. Check database integrity
echo "Checking database integrity..."
sqlite3 backup-data.db "PRAGMA integrity_check;" | grep -v "ok" && echo "❌ Integrity issues found!"

# 2. Update statistics
echo "Updating query statistics..."
sqlite3 backup-data.db "ANALYZE;"

# 3. Clean up temporary files
echo "Cleaning temporary files..."
rm -f backup-data.db-wal backup-data.db-shm

# 4. Check database size
DB_SIZE=$(du -sh backup-data.db | cut -f1)
echo "📊 Database size: $DB_SIZE"

# 5. Check free space
FREE_SPACE=$(df -h . | awk 'NR==2{print $4}')
echo "💾 Free space: $FREE_SPACE"

echo "✅ Daily maintenance completed"
```

### Weekly Maintenance

```bash
#!/bin/bash
# weekly-maintenance.sh

echo "🗓️ Starting weekly database maintenance..."

# 1. Full vacuum (reclaim space)
echo "Running VACUUM to reclaim space..."
sqlite3 backup-data.db "VACUUM;"

# 2. Clean old export jobs
echo "Cleaning old export job records..."
sqlite3 backup-data.db "
DELETE FROM export_jobs 
WHERE status IN ('completed', 'failed') 
  AND completed_at < datetime('now', '-30 days');
"

# 3. Archive old backup records  
echo "Archiving old backup records..."
sqlite3 backup-data.db "
UPDATE backups 
SET metadata = json_set(COALESCE(metadata, '{}'), '$.archived', 'true')
WHERE created_at < datetime('now', '-90 days');
"

# 4. Backup database file
echo "Creating database backup..."
cp backup-data.db "backup-data.db.backup.$(date +%Y%m%d)"

echo "✅ Weekly maintenance completed"
```

### Emergency Recovery

```bash
#!/bin/bash
# emergency-recovery.sh

echo "🚨 Starting emergency database recovery..."

# 1. Stop all processes using the database
echo "Stopping Motia server..."
pkill -f "motia dev"

# 2. Backup corrupted database
echo "Backing up corrupted database..."
cp backup-data.db "backup-data.db.corrupted.$(date +%Y%m%d%H%M%S)"

# 3. Restore from latest backup
LATEST_BACKUP=$(ls -t backup-data.db.backup.* | head -1)
if [ -f "$LATEST_BACKUP" ]; then
  echo "Restoring from $LATEST_BACKUP..."
  cp "$LATEST_BACKUP" backup-data.db
else
  echo "❌ No backup found! Creating fresh database..."
  rm backup-data.db
fi

# 4. Run integrity check
echo "Checking restored database integrity..."
sqlite3 backup-data.db "PRAGMA integrity_check;"

# 5. Re-run migrations if needed
echo "Checking migration status..."
cd libs/accounts-backup
npx ts-node -e "
import { DatabaseManager } from './src/database/database';
const db = DatabaseManager.getInstance('./../../backup-workflows/backup-data.db');
db.getMigrationStatus().then(status => {
  console.log('Migration status:', status);
  process.exit(0);
});
"

# 6. Restart services
echo "Restarting Motia server..."
cd ../../backup-workflows
nohup npx motia dev --port 3002 > motia.log 2>&1 &

echo "✅ Emergency recovery completed"
```

## 📊 Advanced Queries

### Customer Analytics

```sql
-- Customer backup activity report
SELECT 
  c.customer_name,
  COUNT(DISTINCT b.backup_id) as backup_count,
  MAX(b.created_at) as last_backup,
  SUM(b.file_size) / 1024 / 1024 as total_mb,
  AVG(b.file_size) / 1024 as avg_kb,
  COUNT(DISTINCT tct.conversation_id) as conversation_count,
  COUNT(DISTINCT lt.id) as trace_count
FROM customers c
LEFT JOIN backups b ON c.customer_id = b.customer_id
LEFT JOIN tavus_conversation_transcripts tct ON c.customer_id = tct.customer_id
LEFT JOIN langfuse_traces lt ON c.customer_id = lt.customer_id
WHERE c.is_active = TRUE
GROUP BY c.customer_id, c.customer_name
ORDER BY total_mb DESC;
```

### Service Usage Analytics

```sql
-- API usage and costs tracking
SELECT 
  sau.service_name,
  sau.customer_id,
  SUM(sau.daily_quota_used) as total_daily_calls,
  SUM(sau.monthly_quota_used) as total_monthly_calls,
  AVG(sau.rate_limit_remaining) as avg_rate_limit_remaining,
  COUNT(DISTINCT DATE(sau.last_request_at)) as active_days
FROM service_api_usage sau
JOIN customers c ON sau.customer_id = c.customer_id
WHERE sau.last_request_at > datetime('now', '-30 days')
GROUP BY sau.service_name, sau.customer_id
ORDER BY total_monthly_calls DESC;
```

### Performance Analytics

```sql
-- Job execution performance
SELECT 
  service_name,
  export_type,
  AVG(CASE 
    WHEN completed_at IS NOT NULL AND started_at IS NOT NULL 
    THEN (julianday(completed_at) - julianday(started_at)) * 24 * 60 
    ELSE NULL 
  END) as avg_duration_minutes,
  AVG(records_processed) as avg_records,
  AVG(progress_percentage) as avg_completion,
  COUNT(CASE WHEN status = 'completed' THEN 1 END) as completed_jobs,
  COUNT(CASE WHEN status = 'failed' THEN 1 END) as failed_jobs
FROM export_jobs
WHERE started_at > datetime('now', '-30 days')
GROUP BY service_name, export_type
ORDER BY avg_duration_minutes DESC;
```

Your database management system is now fully configured for production monitoring and maintenance! 🚀