# 🚀 BuzzTrail Backup System Setup Guide

## Quick Start (5 Minutes)

### Prerequisites
- Node.js 18+
- pnpm package manager
- Git

### 1. Initial Setup

```bash
# Navigate to the project root
cd /path/to/buzztrail/extension

# Install dependencies
pnpm install

# Build all libraries
pnpm nx build shared-database
pnpm nx build accounts-backup
pnpm nx build backup-workflows
```

### 2. Start the Backup System

```bash
# Navigate to backup-workflows directory
cd backup-workflows

# Start Motia server with visual workbench
npx motia dev --port 3002
```

### 3. Access the System

- **Motia Workbench**: http://localhost:3002/
- **Backup API**: http://localhost:3002/backup/trigger  
- **Cleanup API**: http://localhost:3002/cleanup/trigger

## 📋 Complete Setup Instructions

### Step 1: Environment Verification

```bash
# Check Node.js version (requires 18+)
node --version

# Check pnpm installation
pnpm --version

# If pnpm is not installed:
npm install -g pnpm
```

### Step 2: Project Setup

```bash
# Clone and navigate to project
cd /Users/lars/mycode/buzztrail/extension

# Install all dependencies
pnpm install

# Verify project structure
ls -la
# Should see: backup-workflows/, libs/, documentation/, etc.
```

### Step 3: Build Dependencies

```bash
# Build shared database schemas (required first)
pnpm nx build shared-database
# ✅ Output: TypeScript schemas compiled successfully

# Build accounts-backup library (includes new database schema)
pnpm nx build accounts-backup  
# ✅ Output: Database migrations and types compiled

# Build backup-workflows application
pnpm nx build backup-workflows
# ✅ Output: Motia workflow steps compiled
```

### Step 4: Database Initialization

The database will be automatically initialized with all new tables on first run:

```bash
# Navigate to backup-workflows
cd backup-workflows

# Run database migrations (automatic on startup)
# The following tables will be created:
# - 16 new tables for Tavus/Langfuse/Backup Management
# - 60+ performance indexes
# - Migration tracking system
```

### Step 5: Start Services

```bash
# Start Motia development server
npx motia dev --port 3002

# Expected output:
# ✅ Server ready and listening on port 3002
# 🔗 Open http://0.0.0.0:3002/ to open workbench 🛠️

# The server will automatically:
# 1. Run database migrations
# 2. Create workflow diagrams  
# 3. Start HTTP API server
# 4. Enable visual monitoring
```

### Step 6: Verify Installation

```bash
# In a new terminal, test the API endpoints:

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

# Expected response:
# {
#   "success": true,
#   "message": "Backup workflow triggered successfully",
#   "timestamp": "2025-09-02T10:00:00.000Z"
# }

# Test cleanup trigger  
curl -X POST http://localhost:3002/cleanup/trigger \
  -H "Content-Type: application/json" \
  -d '{"retentionDays": 30}'
```

## 🔧 Configuration Options

### Database Configuration

The system uses SQLite by default. To customize the database location:

```typescript
// In your code:
const db = DatabaseManager.getInstance('./custom-backup-data.db');
```

### Motia Port Configuration

```bash
# Use a different port (3003 is reserved for slide-system)
npx motia dev --port 3004

# Access at: http://localhost:3004/
```

### Environment Variables

Create a `.env` file in `backup-workflows/`:

```env
# Database settings
DATABASE_PATH=./backup-data.db
DATABASE_BACKUP_DIR=./backup-files

# API settings  
MOTIA_PORT=3002
MOTIA_HOST=0.0.0.0

# Service API keys (when ready)
TAVUS_API_KEY=your-tavus-api-key
LANGFUSE_API_KEY=your-langfuse-api-key
LANGFUSE_BASE_URL=https://your-langfuse-instance.com
```

## 🧪 Testing Your Setup

### 1. Run Migration Tests

```bash
# Navigate to accounts-backup library
cd libs/accounts-backup

# Run comprehensive migration tests
npx ts-node src/test-migrations.ts

# Expected output:
# 🚀 Starting database migration tests...
# ✅ Customer creation: PASS
# ✅ Tavus integration: PASS  
# ✅ Langfuse integration: PASS
# ✅ Backup management: PASS
# ✅ Query performance: PASS (<50ms)
# 🎉 All migration tests passed successfully!
```

### 2. Test Motia Workflows

```bash
# Access Motia workbench at http://localhost:3002/
# You should see:
# 1. Visual workflow diagrams for backup and cleanup flows
# 2. Step-by-step execution monitoring
# 3. Real-time logs and state inspection
```

### 3. Test Database Operations

```bash
# Connect to database and verify tables
sqlite3 backup-workflows/backup-data.db

# Check migration status
.tables
# Should show: customers, backups, tavus_*, langfuse_*, backup_*, etc.

# Check migration history  
SELECT * FROM migrations;
# Should show 4 completed migrations

.quit
```

## 📊 Monitoring and Logs

### Motia Workbench Dashboard

Access http://localhost:3002/ to view:

- **Flow Diagrams**: Visual representation of backup workflows
- **Execution Timeline**: Step-by-step workflow execution history
- **State Inspector**: View workflow data between steps  
- **Logs**: Centralized logging with emoji indicators
- **API Explorer**: Test endpoints directly from the interface

### Log Levels and Indicators

```
🔧 Initialization operations
💾 Backup execution  
🧹 Cleanup operations
✅ Success indicators
❌ Error indicators  
📊 Statistical information
⚡ Performance metrics
🎯 Completion status
```

### Database Monitoring

```bash
# Check database size
ls -lah backup-workflows/backup-data.db

# Monitor active connections (if needed)
lsof -n | grep backup-data.db

# Check table sizes
sqlite3 backup-data.db "SELECT name, COUNT(*) FROM sqlite_master WHERE type='table' GROUP BY name;"
```

## 🚨 Troubleshooting

### Common Issues

#### Port Already in Use
```bash
# If port 3002 is busy (use 3004, not 3003 which is reserved):
npx motia dev --port 3004

# Or kill existing processes:
lsof -ti:3002 | xargs kill
```

#### Database Permission Issues
```bash
# Ensure proper permissions
chmod 755 backup-workflows/
chmod 644 backup-workflows/backup-data.db
```

#### Build Failures
```bash
# Clean and rebuild
pnpm nx reset
pnpm nx build shared-database
pnpm nx build accounts-backup
pnpm nx build backup-workflows
```

#### Migration Issues
```bash
# Check migration status
cd libs/accounts-backup
npx ts-node -e "
import { DatabaseManager } from './src/database/database';
const db = DatabaseManager.getInstance('./test.db');
console.log(await db.getMigrationStatus());
"
```

### Log Locations

- **Motia Logs**: Displayed in terminal and workbench interface
- **Database Logs**: SQLite operations logged to console
- **Migration Logs**: Detailed migration execution logs
- **API Logs**: HTTP request/response logging

### Performance Issues

```bash
# Check database query performance
sqlite3 backup-data.db "EXPLAIN QUERY PLAN SELECT * FROM customers;"

# Monitor memory usage  
top -p $(pgrep -f "motia dev")

# Check disk space
df -h .
```

## 🎯 Next Steps

Once setup is complete:

1. **Configure Service APIs**: Add Tavus and Langfuse API credentials
2. **Create Customers**: Use the database methods to add customer accounts
3. **Test Backup Flows**: Trigger backups and monitor execution
4. **Schedule Automation**: Set up automated backup schedules
5. **Monitor Performance**: Use Motia workbench for ongoing monitoring

Your BuzzTrail backup system is now ready for production use! 🚀