// File-based backup API that reads from actual backup files import * as fs from 'fs-extra'; import * as path from 'path'; export interface Backup { backup_id: string; customer_id: string; customer_name: string; service: string; backup_type: string; file_path: string; file_size: number; checksum?: string; created_at: string; expires_at?: string; metadata?: BackupMetadata; } export interface BackupMetadata { environment: string; personas_count: number; conversations_count: number; replicas_count: number; objectives_count: number; guardrails_count: number; api_status: string; } export interface TavusBackupData { account_info: { id: string; name: string; apiKey?: string; environment: string; }; backup_timestamp: string; personas: { persona_id: string; persona_name: string; pipeline_mode?: string; system_prompt?: string; context?: string; layers?: unknown; objectives_id?: string | null; guardrails_id?: string | null; greeting?: string; default_replica_id?: string; document_ids?: string[]; document_tags?: string[]; created_at?: string; updated_at?: string; }[]; conversations?: unknown[]; replicas?: unknown[]; objectives?: unknown[]; guardrails?: unknown[]; } export class FileBackupAPI { private backupBasePath: string; constructor(backupPath = '../../backup-data') { this.backupBasePath = path.resolve(__dirname, backupPath); } async getBackups(): Promise { const backups: Backup[] = []; const customersPath = path.join(this.backupBasePath, 'customers'); if (!await fs.pathExists(customersPath)) { console.warn(`Backup directory not found: ${customersPath}`); return backups; } try { const customerDirs = await fs.readdir(customersPath); for (const customerDir of customerDirs) { const customerPath = path.join(customersPath, customerDir); const stat = await fs.stat(customerPath); if (!stat.isDirectory()) continue; const timestampDirs = await fs.readdir(customerPath); for (const timestampDir of timestampDirs) { const backupPath = path.join(customerPath, timestampDir); const backupStat = await fs.stat(backupPath); if (!backupStat.isDirectory()) continue; // Check for tavus-data.json const tavusDataPath = path.join(backupPath, 'tavus-data.json'); if (await fs.pathExists(tavusDataPath)) { const fileStats = await fs.stat(tavusDataPath); const backupData = await this.loadTavusBackupData(customerDir, timestampDir); if (backupData) { backups.push({ backup_id: `${customerDir}-${timestampDir}`, customer_id: customerDir, customer_name: backupData.account_info.name, service: 'tavus', backup_type: 'full', created_at: backupData.backup_timestamp, file_size: fileStats.size, file_path: tavusDataPath, metadata: { environment: backupData.account_info.environment, personas_count: backupData.personas?.length || 0, conversations_count: backupData.conversations?.length || 0, replicas_count: backupData.replicas?.length || 0, objectives_count: backupData.objectives?.length || 0, guardrails_count: backupData.guardrails?.length || 0, api_status: 'active' } }); } } } } } catch (_error) { console.error('Error reading backup files:', error); } return backups.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime()); } async getBackupById(backupId: string): Promise { const backups = await this.getBackups(); return backups.find(b => b.backup_id === backupId) || null; } async getBackupData(backupId: string): Promise { // Parse backup ID (format: customer-id-timestamp) const lastDashIndex = backupId.lastIndexOf('-'); if (lastDashIndex === -1) { throw new Error(`Invalid backup ID format: ${backupId}`); } const customerId = backupId.substring(0, lastDashIndex); const timestamp = backupId.substring(lastDashIndex + 1); const tavusData = await this.loadTavusBackupData(customerId, timestamp); if (tavusData) { return { personas: tavusData.personas || [], conversations: tavusData.conversations || [], replicas: tavusData.replicas || [], objectives: tavusData.objectives || [], guardrails: tavusData.guardrails || [], api_status: 'active', backup_timestamp: tavusData.backup_timestamp, account_info: tavusData.account_info }; } throw new Error(`Backup not found: ${backupId}`); } private async loadTavusBackupData(customerId: string, timestamp: string): Promise { const filePath = path.join(this.backupBasePath, 'customers', customerId, timestamp, 'tavus-data.json'); if (!await fs.pathExists(filePath)) { return null; } try { const data = await fs.readJSON(filePath); return data as TavusBackupData; } catch (_error) { console.error(`Failed to load Tavus backup data from ${filePath}:`, error); return null; } } async getBackupsByService(service: string): Promise { const allBackups = await this.getBackups(); return allBackups.filter(backup => backup.service === service); } async runBackup(service = 'tavus', customerId?: string): Promise { // Simulate backup operation await new Promise(resolve => setTimeout(resolve, 2000)); return { success: true, message: `${service} backup completed successfully`, backup_id: `${service}-backup-${Date.now()}`, output: `Backup completed for ${service} service${customerId ? ` for customer ${customerId}` : ''}` }; } async restoreBackup(backupId: string, options: unknown): Promise { await new Promise(resolve => setTimeout(resolve, 1500)); return { success: true, message: `Backup ${backupId} restore initiated`, restoredItems: options.selectedItems || [] }; } async restoreIndividualItem(backupId: string, itemType: string, itemId: string): Promise { await new Promise(resolve => setTimeout(resolve, 1000)); return { success: true, message: `${itemType} ${itemId} restored successfully`, restoredItem: { type: itemType, id: itemId, timestamp: new Date().toISOString() } }; } async promoteToEnvironment(backupId: string, targetEnvironment: string, options: unknown): Promise { await new Promise(resolve => setTimeout(resolve, 2000)); const actionType = options.isDemotion ? 'demoted' : 'promoted'; return { success: true, message: `Items ${actionType} to ${targetEnvironment}`, promotedItems: options.selectedItems || [], targetEnvironment, customerId: options.customerId, customerName: options.customerName, sourceEnvironment: options.sourceEnvironment }; } } // Export singleton instance for browser compatibility export const fileBackupAPI = new FileBackupAPI();