// Frontend-compatible backup API that loads real backup data // Reads from actual backup files via HTTP requests or static hosting import { CustomerConfigService } from '../stores/customer-config'; import { RealBackupLoader } from './real-backup-loader'; export type ServiceType = 'tavus' | 'vapi' | 'other'; export interface ServiceConfig { name: string; displayName: string; backupScript: string; dataTypes: string[]; } 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?: unknown; } const serviceConfigs: Record = { tavus: { name: 'tavus', displayName: 'Tavus', backupScript: 'tavus-backup.js', dataTypes: ['personas', 'conversations', 'replicas', 'objectives', 'guardrails'] }, vapi: { name: 'vapi', displayName: 'Vapi', backupScript: 'vapi-backup.js', dataTypes: ['assistants', 'phone_numbers', 'calls', 'templates'] }, other: { name: 'other', displayName: 'Other Service', backupScript: 'generic-backup.js', dataTypes: ['data'] } }; // Mock data for development (in production, would fetch from real database) // Follows the corrected model: 3 Environments × Multiple Real Customers const mockBackups: Backup[] = [ // PRODUCTION ENVIRONMENT - Acme Corp Customer { backup_id: 'backup-acme-prod-2025-09-02T15-38-13-283Z', customer_id: 'customer-acme-corp-456', customer_name: 'Acme Corp', service: 'tavus', backup_type: 'full', file_path: 'backup-data/prod/acme-corp/2025-09-02T15-38-13-283Z/tavus-data.json', file_size: 2351, checksum: 'sha256-acme-prod-hash', created_at: '2025-09-02T15:38:13.284Z', expires_at: '2025-10-02T15:38:13.284Z', metadata: { customer_name: 'Acme Corp', environment: 'production', tavus_environment_id: 'env-tavus-prod-123', service: 'tavus', personas_count: 12, conversations_count: 845, replicas_count: 8, objectives_count: 6, guardrails_count: 9, api_status: 'active', personas: [ { global_persona_id: 'persona-acme-sales-789', name: 'Acme Sales Assistant', customer_id: 'customer-acme-corp-456' }, { global_persona_id: 'persona-acme-support-101', name: 'Acme Support Bot', customer_id: 'customer-acme-corp-456' }, { global_persona_id: 'persona-acme-demo-202', name: 'Acme Demo Bot', customer_id: 'customer-acme-corp-456' } ] } }, // PRODUCTION ENVIRONMENT - Beta Inc Customer { backup_id: 'backup-beta-prod-2025-09-02T16-22-45-891Z', customer_id: 'customer-beta-inc-789', customer_name: 'Beta Inc', service: 'tavus', backup_type: 'full', file_path: 'backup-data/prod/beta-inc/2025-09-02T16-22-45-891Z/tavus-data.json', file_size: 1567, checksum: 'sha256-beta-prod-hash', created_at: '2025-09-02T16:22:45.891Z', expires_at: '2025-10-02T16:22:45.891Z', metadata: { customer_name: 'Beta Inc', environment: 'production', tavus_environment_id: 'env-tavus-prod-123', service: 'tavus', personas_count: 5, conversations_count: 312, replicas_count: 3, objectives_count: 4, guardrails_count: 7, api_status: 'active', personas: [ { global_persona_id: 'persona-beta-onboard-303', name: 'Beta Onboarding Assistant', customer_id: 'customer-beta-inc-789' }, { global_persona_id: 'persona-beta-tech-404', name: 'Beta Tech Support', customer_id: 'customer-beta-inc-789' } ] } }, // STAGING ENVIRONMENT - Acme Corp Customer (same customer, different environment) { backup_id: 'backup-acme-staging-2025-09-09T20-15-30-123Z', customer_id: 'customer-acme-corp-456', customer_name: 'Acme Corp', service: 'tavus', backup_type: 'full', file_path: 'backup-data/staging/acme-corp/2025-09-09T20-15-30-123Z/tavus-data.json', file_size: 1248, checksum: 'sha256-acme-staging-hash', created_at: '2025-09-09T20:15:30.123Z', expires_at: '2025-10-09T20:15:30.123Z', metadata: { customer_name: 'Acme Corp', environment: 'staging', tavus_environment_id: 'env-tavus-staging-124', service: 'tavus', personas_count: 2, conversations_count: 67, replicas_count: 2, objectives_count: 3, guardrails_count: 5, api_status: 'active', personas: [ { global_persona_id: 'persona-acme-sales-789', name: 'Acme Sales Assistant', customer_id: 'customer-acme-corp-456' }, // Promoted from prod { global_persona_id: 'persona-acme-demo-202', name: 'Acme Demo Bot', customer_id: 'customer-acme-corp-456' } // Promoted from prod ] } }, // TESTING ENVIRONMENT - Acme Corp Customer (same customer, testing environment) { backup_id: 'backup-acme-testing-2025-09-09T19-45-12-456Z', customer_id: 'customer-acme-corp-456', customer_name: 'Acme Corp', service: 'tavus', backup_type: 'full', file_path: 'backup-data/testing/acme-corp/2025-09-09T19-45-12-456Z/tavus-data.json', file_size: 892, checksum: 'sha256-acme-testing-hash', created_at: '2025-09-09T19:45:12.456Z', expires_at: '2025-10-09T19:45:12.456Z', metadata: { customer_name: 'Acme Corp', environment: 'testing', tavus_environment_id: 'env-tavus-testing-125', service: 'tavus', personas_count: 1, conversations_count: 23, replicas_count: 1, objectives_count: 2, guardrails_count: 3, api_status: 'active', personas: [ { global_persona_id: 'persona-acme-sales-789', name: 'Acme Sales Assistant', customer_id: 'customer-acme-corp-456' } // Demoted from staging ] } }, // TESTING ENVIRONMENT - Beta Inc Customer (different customer, testing environment) { backup_id: 'backup-beta-testing-2025-09-08T14-30-22-678Z', customer_id: 'customer-beta-inc-789', customer_name: 'Beta Inc', service: 'tavus', backup_type: 'full', file_path: 'backup-data/testing/beta-inc/2025-09-08T14-30-22-678Z/tavus-data.json', file_size: 445, checksum: 'sha256-beta-testing-hash', created_at: '2025-09-08T14:30:22.678Z', expires_at: '2025-10-08T14:30:22.678Z', metadata: { customer_name: 'Beta Inc', environment: 'testing', tavus_environment_id: 'env-tavus-testing-125', service: 'tavus', personas_count: 1, conversations_count: 8, replicas_count: 1, objectives_count: 1, guardrails_count: 2, api_status: 'active', personas: [ { global_persona_id: 'persona-beta-tech-404', name: 'Beta Tech Support', customer_id: 'customer-beta-inc-789' } // Demoted for testing ] } }, // PRODUCTION ENVIRONMENT - Unassigned/Catch-all Customer for new personas { backup_id: 'backup-unassigned-prod-2025-09-10T10-15-30-789Z', customer_id: 'customer-unassigned-catchall-000', customer_name: '⚠️ Unassigned Personas', service: 'tavus', backup_type: 'full', file_path: 'backup-data/prod/unassigned/2025-09-10T10-15-30-789Z/tavus-data.json', file_size: 892, checksum: 'sha256-unassigned-prod-hash', created_at: '2025-09-10T10:15:30.789Z', expires_at: '2025-11-10T10:15:30.789Z', metadata: { customer_name: '⚠️ Unassigned Personas', environment: 'production', tavus_environment_id: 'env-tavus-prod-123', service: 'tavus', personas_count: 3, conversations_count: 45, replicas_count: 2, objectives_count: 1, guardrails_count: 1, api_status: 'active', personas: [ { global_persona_id: 'persona-unassigned-new-001', name: 'Mystery Sales Bot', customer_id: 'customer-unassigned-catchall-000', is_unassigned: true }, { global_persona_id: 'persona-unassigned-new-002', name: 'Unknown Support Agent', customer_id: 'customer-unassigned-catchall-000', is_unassigned: true }, { global_persona_id: 'persona-unassigned-new-003', name: 'Untitled Persona', customer_id: 'customer-unassigned-catchall-000', is_unassigned: true } ] } }, // STAGING ENVIRONMENT - Unassigned/Catch-all Customer for new personas { backup_id: 'backup-unassigned-staging-2025-09-10T09-45-15-456Z', customer_id: 'customer-unassigned-catchall-000', customer_name: '⚠️ Unassigned Personas', service: 'tavus', backup_type: 'full', file_path: 'backup-data/staging/unassigned/2025-09-10T09-45-15-456Z/tavus-data.json', file_size: 534, checksum: 'sha256-unassigned-staging-hash', created_at: '2025-09-10T09:45:15.456Z', expires_at: '2025-11-10T09:45:15.456Z', metadata: { customer_name: '⚠️ Unassigned Personas', environment: 'staging', tavus_environment_id: 'env-tavus-staging-124', service: 'tavus', personas_count: 2, conversations_count: 12, replicas_count: 1, objectives_count: 1, guardrails_count: 1, api_status: 'active', personas: [ { global_persona_id: 'persona-unassigned-test-004', name: 'Test Persona A', customer_id: 'customer-unassigned-catchall-000', is_unassigned: true }, { global_persona_id: 'persona-unassigned-test-005', name: 'Development Bot', customer_id: 'customer-unassigned-catchall-000', is_unassigned: true } ] } } ]; export class BackupAPI { private realBackupLoader: RealBackupLoader; constructor() { this.realBackupLoader = RealBackupLoader.getInstance(); } async getBackups(): Promise { // Simulate API call delay await new Promise(resolve => setTimeout(resolve, 500)); // Initialize customer configurations if not already done await CustomerConfigService.initialize(); try { // Load real backup data console.log('🔄 Loading real backup data...'); const realBackups = await this.realBackupLoader.loadRealBackups(); console.log(`✅ Loaded ${realBackups.length} real backups`); if (realBackups.length > 0) { // Auto-import customer configs from real backups const customerImportData = realBackups.map(backup => ({ customer_id: backup.customer_id, customer_name: backup.customer_name, metadata: backup.metadata })); await CustomerConfigService.importFromBackups(customerImportData); } return realBackups; } catch (_error) { console.error('❌ Failed to load real backups:', error); return []; } } async getBackupById(backupId: string): Promise { await new Promise(resolve => setTimeout(resolve, 200)); // In production: fetch(`/api/backups/${backupId}`) const backup = mockBackups.find(b => b.backup_id === backupId); return backup || null; } async getBackupsByService(service: ServiceType): Promise { await new Promise(resolve => setTimeout(resolve, 300)); // In production: fetch(`/api/backups?service=${service}`) return mockBackups.filter(backup => backup.service === service); } async getBackupData(backupId: string): Promise { console.log(`🔍 getBackupData called with backupId: ${backupId}`); await new Promise(resolve => setTimeout(resolve, 400)); // Try to get real backup data first try { console.log(`📦 Attempting to load real backup data for: ${backupId}`); const realBackupData = await this.realBackupLoader.getRealBackupData(backupId); if (realBackupData) { console.log(`✅ Loaded real backup data for ${backupId}`, realBackupData); return realBackupData; } else { console.log(`⚠️ Real backup data was null for ${backupId}`); } } catch (_error) { console.warn(`⚠️ Failed to load real backup data for ${backupId}:`, error); } // Fallback to mock data console.log(`📋 Using mock data for backup ${backupId}`); const backup = await this.getBackupById(backupId); if (!backup) { throw new Error('Backup not found'); } // Mock backup data based on service if (backup.service === 'tavus') { // Check if this is an unassigned personas backup const isUnassignedBackup = backup.customer_id === 'customer-unassigned-catchall-000'; let personas = []; if (isUnassignedBackup && backup.metadata?.personas) { // Use the specific unassigned persona data from metadata personas = backup.metadata.personas.map((persona: unknown) => ({ persona_id: persona.global_persona_id.replace('persona-', 'persona_'), persona_name: persona.name, global_persona_id: persona.global_persona_id, customer_id: persona.customer_id, is_unassigned: persona.is_unassigned || false, persona_type: 'unassigned', system_prompt: `This persona was created directly in Tavus but hasn't been assigned to a specific customer yet. Name: ${persona.name}. It needs to be reviewed and assigned to the appropriate customer account.`, needs_assignment: true })); } else { // Regular assigned personas with realistic prompts and data const personaTemplates = [ { name: 'Sales Assistant', type: 'personal', prompt: `You are an expert sales assistant for ${backup.customer_name}. Your primary goals are: 1. Qualify prospects by understanding their needs, budget, and timeline 2. Demonstrate deep product knowledge and business value 3. Handle objections professionally and build trust 4. Guide conversations toward scheduling demos or meetings 5. Always maintain a helpful, consultative approach Key principles: - Ask open-ended questions to understand customer pain points - Provide specific, relevant examples and case studies - Never be pushy or aggressive - focus on value creation - If you don't know something, be honest and offer to follow up - Always end calls with clear next steps Voice and tone: Professional, friendly, knowledgeable, and solution-oriented.`, objectives: [ { content: 'Qualify at least 3 key criteria: budget, authority, need, timeline' }, { content: 'Schedule qualified demos or discovery calls' }, { content: 'Gather contact information and preferred communication methods' } ], guardrails: [ { content: 'Never promise features that are not currently available' }, { content: 'Do not discuss competitor pricing or bad-mouth competitors' }, { content: 'Always respect prospect\'s time constraints and preferences' } ] }, { name: 'Support Agent', type: 'draft', prompt: `You are a customer support specialist for ${backup.customer_name}. Your role is to: 1. Provide accurate, helpful solutions to customer problems 2. Escalate complex technical issues to appropriate teams 3. Maintain detailed records of customer interactions 4. Ensure customer satisfaction and positive experience 5. Identify opportunities for account expansion when appropriate Support guidelines: - Always start by acknowledging the customer's concern - Ask clarifying questions to fully understand the issue - Provide step-by-step solutions when possible - Set realistic expectations for resolution timelines - Follow up to ensure problems are fully resolved Remember: Every interaction is an opportunity to strengthen the customer relationship.`, objectives: [ { content: 'Resolve customer issues within first contact when possible' }, { content: 'Maintain customer satisfaction scores above 4.5/5' }, { content: 'Document all interactions for knowledge base improvement' } ], guardrails: [ { content: 'Never provide account access or sensitive information without verification' }, { content: 'Do not make commitments about features or timelines without approval' }, { content: 'Always escalate billing disputes to the appropriate team' } ] }, { name: 'Onboarding Specialist', type: 'personal', prompt: `You are an onboarding specialist for ${backup.customer_name}, focused on helping new customers succeed. Your responsibilities: 1. Guide new users through product setup and configuration 2. Provide comprehensive training on key features and best practices 3. Identify potential challenges and proactively address them 4. Set customers up for long-term success and engagement 5. Collect feedback to improve the onboarding process Onboarding best practices: - Customize guidance based on customer's specific use case - Break complex processes into manageable steps - Provide multiple learning formats (demos, docs, hands-on) - Check for understanding before moving to next topics - Celebrate quick wins and progress milestones Goal: Transform new customers into confident, successful power users.`, objectives: [ { content: 'Complete initial setup within first week' }, { content: 'Achieve 80% feature adoption in first 30 days' }, { content: 'Schedule success check-ins at 7, 30, and 90 days' } ], guardrails: [ { content: 'Do not overwhelm customers with too many features at once' }, { content: 'Always confirm customer understanding before proceeding' }, { content: 'Respect customer\'s preferred learning pace and style' } ] } ]; personas = Array.from({ length: backup.metadata?.personas_count || 0 }, (_, i) => { const template = personaTemplates[i % personaTemplates.length]; const personaNum = i + 1; return { persona_id: `persona_${personaNum}`, persona_name: `${backup.customer_name} ${template.name} ${personaNum > 3 ? personaNum : ''}`.trim(), name: `${backup.customer_name} ${template.name} ${personaNum > 3 ? personaNum : ''}`.trim(), global_persona_id: backup.metadata?.personas?.[i]?.global_persona_id || `persona-${backup.customer_name.toLowerCase().replace(' ', '-')}-${template.name.toLowerCase().replace(' ', '-')}-${personaNum}`, customer_id: backup.customer_id, is_unassigned: false, persona_type: template.type, system_prompt: template.prompt, prompt_template: template.prompt, description: `Specialized ${template.name.toLowerCase()} for ${backup.customer_name} operations`, voice_engine: i % 2 === 0 ? 'eleven-labs' : 'azure-tts', voice_id: `voice_${personaNum}_${template.name.toLowerCase().replace(' ', '_')}`, language: 'en-US', default_replica_id: i < 2 ? `replica_${personaNum}` : null, objectives: template.objectives, guardrails: template.guardrails }; }); } return { personas, conversations: Array.from({ length: backup.metadata?.conversations_count || 0 }, (_, i) => ({ conversation_id: `conv_${i + 1}`, title: `Conversation ${i + 1}`, created_at: new Date(Date.now() - i * 86400000).toISOString() })), replicas: Array.from({ length: backup.metadata?.replicas_count || 0 }, (_, i) => ({ replica_id: `replica_${i + 1}`, replica_name: `Replica ${i + 1}`, status: 'active' })), objectives: Array.from({ length: backup.metadata?.objectives_count || 0 }, (_, i) => ({ objective_id: `obj_${i + 1}`, content: `This is the content for Objective ${i + 1}. It outlines specific goals and targets that should be achieved.` })), guardrails: Array.from({ length: backup.metadata?.guardrails_count || 0 }, (_, i) => ({ guardrail_id: `guard_${i + 1}`, content: `This is the content for Guardrail ${i + 1}. It defines important safety and behavioral constraints.` })) }; } else if (backup.service === 'vapi') { return { assistants: Array.from({ length: backup.metadata?.assistants_count || 0 }, (_, i) => ({ id: `asst_${i + 1}`, name: `Assistant ${i + 1}`, model: 'gpt-4' })), phone_numbers: Array.from({ length: backup.metadata?.phone_numbers_count || 0 }, (_, i) => ({ id: `phone_${i + 1}`, number: `+1555000${String(i + 1).padStart(4, '0')}` })), calls: Array.from({ length: backup.metadata?.calls_count || 0 }, (_, i) => ({ id: `call_${i + 1}`, duration: Math.floor(Math.random() * 300) + 30, status: 'completed' })), templates: Array.from({ length: backup.metadata?.templates_count || 0 }, (_, i) => ({ id: `tmpl_${i + 1}`, name: `Template ${i + 1}` })) }; } return {}; } async runBackup(service: ServiceType = 'tavus', customerId?: string): Promise { if (service !== 'tavus') { // For non-Tavus services, keep the simulation for now await new Promise(resolve => setTimeout(resolve, 2000)); return { success: true, message: `${serviceConfigs[service].displayName} backup completed successfully`, backup_id: `${service}-backup-${Date.now()}`, output: `Backup completed for ${service} service` }; } // For Tavus backups, call the backup-workflows service try { console.log('🚀 Starting real Tavus backup via backup-workflows...'); // Call the backup-workflows service instead of running TavusClient in browser const response = await fetch('http://localhost:3003/api/backup/tavus', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ environment: 'testing', apiKey: 'test-api-key', customerId: customerId || 'backup-manager-request', customerName: 'Backup Manager Request' }) }); if (!response.ok) { throw new Error(`Backup service responded with ${response.status}: ${response.statusText}`); } const result = await response.json(); console.log('✅ Backup service response:', result); // Create mock backup data structure for the UI const backupData = { account_info: { id: result.backupId || customerId, name: 'Testing Account', environment: 'testing' }, backup_timestamp: new Date().toISOString(), personas: Array(result.recordCount || 2).fill(null).map((_, i) => ({ persona_id: `persona-${i + 1}`, persona_name: `Persona ${i + 1}`, persona_type: 'personal' })), conversations: [], replicas: [], api_status: 'active' }; console.log('✅ Tavus backup completed successfully'); return { success: true, message: `Tavus backup completed successfully`, backup_id: `tavus-backup-${Date.now()}`, output: `Backed up ${backupData.personas.length} personas, ${backupData.conversations.length} conversations, ${backupData.replicas.length} replicas`, environment: backupData.account_info.environment, recordCount: backupData.personas.length, backupData: backupData }; } catch (_error) { console.error('❌ Tavus backup failed:', error); return { success: false, message: 'Tavus backup failed', error: error instanceof Error ? error.message : 'Unknown error', output: `Failed to backup Tavus data: ${error instanceof Error ? error.message : 'Unknown error'}` }; } } async restoreBackup(backupId: string, options: unknown): Promise { await new Promise(resolve => setTimeout(resolve, 1500)); // In production: POST /api/backups/${backupId}/restore 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)); // In production: POST /api/backups/${backupId}/restore-item 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)); // In production: POST /api/backups/${backupId}/promote const actionType = options.isDemotion ? 'demoted' : 'promoted'; // Log customer relationship preservation details if (options.preserveCustomerRelationships && options.personaDetails) { console.log(`🔄 ${actionType.toUpperCase()} with customer relationship preservation:`); console.log(` Customer: ${options.customerName} (${options.customerId})`); console.log(` Source Environment: ${options.sourceEnvironment}`); console.log(` Target Environment: ${targetEnvironment}`); console.log(` Personas being ${actionType}:`, options.personaDetails.map((p: unknown) => ({ name: p.name, global_persona_id: p.global_persona_id, customer_id: p.customer_id }))); } return { success: true, message: `Items ${actionType} to ${targetEnvironment}`, promotedItems: options.selectedItems || [], targetEnvironment, customerId: options.customerId, customerName: options.customerName, sourceEnvironment: options.sourceEnvironment, preservedRelationships: options.preserveCustomerRelationships || false, personaDetails: options.personaDetails || [] }; } getServiceConfig(service: ServiceType): ServiceConfig { return serviceConfigs[service]; } getAvailableServices(): ServiceType[] { return Object.keys(serviceConfigs) as ServiceType[]; } // Data Promotion APIs async promoteToTestData(options: { backupIds: string[]; targetLocation?: string; includeUnassigned?: boolean; customerNameOverrides?: Record; }): Promise<{ success: boolean; promotedBackups: string[]; targetPath: string; message: string; }> { await new Promise(resolve => setTimeout(resolve, 2000)); // Simulate processing time const _targetPath = options.targetLocation || '../fake-tavus-server/backup-data/customers'; const promotedBackups: string[] = []; for (const backupId of options.backupIds) { const backup = mockBackups.find(b => b.backup_id === backupId); if (backup) { const customerDisplayName = await CustomerConfigService.getDisplayName(backup.customer_id); const finalCustomerName = options.customerNameOverrides?.[backup.customer_id] || customerDisplayName; // In production, this would: // 1. Load the backup data from storage // 2. Transform it to fake-tavus-server format // 3. Write to target location // 4. Update fake-tavus-server data structures console.log(`Promoting backup ${backupId} for customer "${finalCustomerName}" to ${_targetPath}`); promotedBackups.push(backupId); } } return { success: true, promotedBackups, _targetPath, message: `Successfully promoted ${promotedBackups.length} backups to test data location.` }; } async validatePromotionTarget(targetPath: string): Promise<{ exists: boolean; writable: boolean; fakeServerDetected: boolean; message: string; }> { await new Promise(resolve => setTimeout(resolve, 500)); // In production, this would check actual file system permissions return { exists: true, writable: true, fakeServerDetected: true, message: 'Target location is valid and fake-tavus-server structure detected.' }; } async getPromotionPreview(backupIds: string[]): Promise<{ totalBackups: number; totalCustomers: number; environmentBreakdown: Record; dataBreakdown: { personas: number; conversations: number; replicas: number; objectives: number; guardrails: number; }; customerList: { customer_id: string; customer_name: string; display_name: string; environment: string; backup_count: number; }[]; }> { await new Promise(resolve => setTimeout(resolve, 300)); const selectedBackups = mockBackups.filter(backup => backupIds.includes(backup.backup_id)); const customerMap = new Map(); const environmentBreakdown: Record = {}; let totalPersonas = 0; let totalConversations = 0; let totalReplicas = 0; let totalObjectives = 0; let totalGuardrails = 0; for (const backup of selectedBackups) { // Count environment breakdown const env = backup.metadata?.environment || 'unknown'; environmentBreakdown[env] = (environmentBreakdown[env] || 0) + 1; // Count data totalPersonas += backup.metadata?.personas_count || 0; totalConversations += backup.metadata?.conversations_count || 0; totalReplicas += backup.metadata?.replicas_count || 0; totalObjectives += backup.metadata?.objectives_count || 0; totalGuardrails += backup.metadata?.guardrails_count || 0; // Track customers if (!customerMap.has(backup.customer_id)) { customerMap.set(backup.customer_id, { customer_id: backup.customer_id, customer_name: backup.customer_name, environment: env, backup_count: 0 }); } customerMap.get(backup.customer_id)!.backup_count++; } const customerList = Array.from(customerMap.values()).map(customer => ({ ...customer, display_name: CustomerConfigService.getDisplayName(customer.customer_id) })); return { totalBackups: selectedBackups.length, totalCustomers: customerMap.size, environmentBreakdown, dataBreakdown: { personas: totalPersonas, conversations: totalConversations, replicas: totalReplicas, objectives: totalObjectives, guardrails: totalGuardrails }, customerList }; } /** * Get the list of Stock personas that are excluded from backups */ getExcludedStockPersonas(): string[] { return this.realBackupLoader.getExcludedStockPersonas(); } // Persona Promotion Analysis APIs async analyzePromotionOpportunities(environments?: ('testing' | 'staging' | 'production')[]): Promise { try { const backupWorkflowsUrl = 'http://localhost:3003'; const queryParams = environments ? `?environments=${environments.join(',')}` : ''; const response = await fetch(`${backupWorkflowsUrl}/api/promotion/analyze${queryParams}`); if (!response.ok) { throw new Error(`API request failed: ${response.status}`); } return await response.json(); } catch (_error) { console.error('Failed to analyze promotion opportunities:', error); return { success: false, error: error instanceof Error ? error.message : 'Unknown error' }; } } async getPersonaPromotionRecommendations(personaName: string): Promise { try { const backupWorkflowsUrl = 'http://localhost:3003'; const response = await fetch(`${backupWorkflowsUrl}/api/promotion/recommendations/${encodeURIComponent(personaName)}`); if (!response.ok) { throw new Error(`API request failed: ${response.status}`); } return await response.json(); } catch (_error) { console.error('Failed to get persona promotion recommendations:', error); return { success: false, error: error instanceof Error ? error.message : 'Unknown error' }; } } } // Export a singleton instance export const backupAPI = new BackupAPI();