import express from 'express'; import cors from 'cors'; import * as fs from 'fs'; import * as path from 'path'; import { TavusBackupJob } from './jobs/tavus-backup.js'; import { PromotionAnalysisAPI } from './api/promotion-analysis.js'; const app = express(); const port = 3003; // Different port from Motia app.use(cors()); app.use(express.json()); // Initialize promotion analysis API const promotionAnalysisAPI = new PromotionAnalysisAPI(); // Health check endpoint app.get('/health', (req, res) => { res.json({ status: 'ok', service: 'backup-workflows-api' }); }); // Tavus backup endpoint app.post('/api/backup/tavus', (req, res) => void (async () => { console.log('🚀 Received backup request:', req.body); try { const { environment, apiKey, customerId, customerName } = req.body; if (!environment || !apiKey) { return res.status(400).json({ success: false, error: 'Missing required fields: environment, apiKey' }); } // Create and run backup job const backupJob = new TavusBackupJob(); const result = await backupJob.runBackup({ environment, apiKey, customerId: customerId || `customer-${environment}-${Date.now()}`, customerName: customerName || `${environment} Customer` }); console.log('✅ Backup completed:', result); res.json({ success: result.success, backupId: result.backupId, recordCount: result.recordCount, error: result.error, message: result.success ? 'Backup completed successfully' : 'Backup failed' }); } catch (error) { console.error('❌ API endpoint error:', error); res.status(500).json({ success: false, error: error instanceof Error ? error.message : 'Unknown error', message: 'Internal server error' }); } })()); // List customers and their backups endpoint app.get('/api/backup/list', (req, res) => void (async () => { console.log('📋 Received backup list request'); try { const projectRoot = path.resolve(__dirname, '../../../../..'); const backupPath = path.join(projectRoot, 'apps/backup-manager/public/backup-data/customers'); console.log(`🔍 Looking for backups in: ${backupPath}`); if (!fs.existsSync(backupPath)) { return res.json({ success: true, customers: [], message: 'No backup directory found' }); } const customers = fs.readdirSync(backupPath, { withFileTypes: true }) .filter(dirent => dirent.isDirectory()) .map(dirent => dirent.name); console.log(`📁 Found customers: ${customers}`); const customerData = []; for (const customerId of customers) { const customerPath = path.join(backupPath, customerId); try { const backups = fs.readdirSync(customerPath, { withFileTypes: true }) .filter(dirent => dirent.isDirectory()) .map(dirent => dirent.name) .sort((a, b) => b.localeCompare(a)); // Latest first // Try to get customer info from the most recent backup let customerName = customerId; if (backups.length > 0) { const recentBackupPath = path.join(customerPath, backups[0], 'tavus-data.json'); if (fs.existsSync(recentBackupPath)) { try { const backupData = JSON.parse(fs.readFileSync(recentBackupPath, 'utf8')); customerName = backupData.account_info?.name || customerId; } catch (error) { console.warn(`⚠️ Could not read backup data for ${customerId}:`, error); } } } customerData.push({ environmentId: customerId, environmentName: customerName, environment: customerId.includes('prod') ? 'production' : customerId.includes('staging') ? 'staging' : customerId.includes('testing') ? 'testing' : 'development', backups: backups }); } catch (error) { console.warn(`⚠️ Error reading customer ${customerId}:`, error); } } console.log(`✅ Returning ${customerData.length} customers with backups`); res.json({ success: true, customers: customerData, message: `Found ${customerData.length} customers` }); } catch (error) { console.error('❌ Backup list error:', error); res.status(500).json({ success: false, error: error instanceof Error ? error.message : 'Unknown error', message: 'Internal server error' }); } })()); // Promotion analysis endpoints app.get('/api/promotion/analyze', (req, res) => void (async () => { console.log('🔍 Received promotion analysis request:', req.query); try { const environments = req.query.environments ? String(req.query.environments).split(',') as ('testing' | 'staging' | 'production')[] : undefined; const result = await promotionAnalysisAPI.analyzePromotionOpportunities({ environments }); console.log('✅ Promotion analysis completed:', result.success); res.json(result); } catch (error) { console.error('❌ Promotion analysis error:', error); res.status(500).json({ success: false, error: error instanceof Error ? error.message : 'Unknown error' }); } })()); app.get('/api/promotion/recommendations/:personaName', (req, res) => void (async () => { console.log('🔍 Received persona recommendations request:', req.params.personaName); try { const { personaName } = req.params; const result = await promotionAnalysisAPI.getPersonaPromotionRecommendations(personaName); console.log('✅ Persona recommendations completed:', result.success); res.json(result); } catch (error) { console.error('❌ Persona recommendations error:', error); res.status(500).json({ success: false, error: error instanceof Error ? error.message : 'Unknown error' }); } })()); app.listen(port, () => { console.log(`🚀 Backup Workflows API running on http://localhost:${port}`); console.log(`🔗 Health check: http://localhost:${port}/health`); console.log(`🔗 Backup endpoint: POST http://localhost:${port}/api/backup/tavus`); console.log(`🔗 List backups: GET http://localhost:${port}/api/backup/list`); console.log(`🔗 Promotion analysis: GET http://localhost:${port}/api/promotion/analyze`); console.log(`🔗 Persona recommendations: GET http://localhost:${port}/api/promotion/recommendations/:personaName`); });