import { logger } from '../utils/logger'; import { IdGenerator as _IdGenerator } from '../utils/id-generator'; import { BackupDataLoader } from './backup-data-loader'; import type { MockConversation, MockReplica, MockPersona, MockVideo, MockSpeech, MockLipsync, MockWebhook } from '../types/mock-types'; import { config } from '../config'; export class MockDataService { private static conversations = new Map(); private static replicas = new Map(); private static personas = new Map(); private static videos = new Map(); private static speech = new Map(); private static lipsyncs = new Map(); private static webhooks = new Map(); private static objectives: unknown[] = []; private static guardrails: unknown[] = []; private static apiKeys = config.apiKeys; static async initialize(): Promise { logger.info('Initializing MockDataService...'); // Initialize backup data loader first const backupLoader = BackupDataLoader.getInstance(); await backupLoader.initialize(); // Load real data from backups await this.loadBackupData(); // Create additional default data if needed this.createDefaultReplicas(); this.createDefaultPersonas(); this.createDefaultConversations(); const summary = backupLoader.getBackupSummary(); logger.info(`MockDataService initialized with real backup data: ${summary.total_personas} personas, ${summary.total_conversations} conversations, ${summary.total_replicas} replicas from ${summary.customers} customer accounts`); } /** * Load real backup data into the mock data maps */ private static async loadBackupData(): Promise { const backupLoader = BackupDataLoader.getInstance(); // Load personas const personas = backupLoader.getAllPersonas(); personas.forEach(persona => { this.personas.set(persona.persona_id, persona); }); // Load conversations const conversations = backupLoader.getAllConversations(); conversations.forEach(conversation => { this.conversations.set(conversation.conversation_id, conversation); }); // Load replicas const replicas = backupLoader.getAllReplicas(); replicas.forEach(replica => { this.replicas.set(replica.replica_id, replica); }); // Load objectives const objectives = backupLoader.getAllObjectives(); this.objectives = objectives; // Load guardrails const guardrails = backupLoader.getAllGuardrails(); this.guardrails = guardrails; logger.info(`Loaded ${personas.length} personas, ${conversations.length} conversations, ${replicas.length} replicas, ${objectives.length} objectives, ${guardrails.length} guardrails from backup data`); } // Authentication methods static validateApiKey(apiKey: string): boolean { return this.apiKeys.includes(apiKey); } static getUserInfo(apiKey: string): { user_id: string; email: string; plan: string; credits_remaining: number; permissions: { conversations: boolean; videos: boolean; speech: boolean; lipsync: boolean; }; } { const userMap = new Map([ ['test-api-key', { user_id: 'user_123456', email: 'test@example.com', plan: 'pro', credits_remaining: 1000, permissions: { conversations: true, videos: true, speech: true, lipsync: true } }], ['mock-tavus-key', { user_id: 'user_456789', email: 'mock@tavus.com', plan: 'enterprise', credits_remaining: 5000, permissions: { conversations: true, videos: true, speech: true, lipsync: true } }], ['buzztrail-test', { user_id: 'user_789012', email: 'dev@buzztrail.ai', plan: 'developer', credits_remaining: 2500, permissions: { conversations: true, videos: true, speech: true, lipsync: true } }] ]); return userMap.get(apiKey) || { user_id: `u_${apiKey.slice(0, 8)}`, email: 'user@example.com', plan: 'basic', credits_remaining: 100, permissions: { conversations: true, videos: false, speech: true, lipsync: false } }; } // Conversation management methods static getConversations(): MockConversation[] { return Array.from(this.conversations.values()); } static getConversation(id: string): MockConversation | null { return this.conversations.get(id) || null; } static createConversation(data: { replica_id: string; persona_id: string; conversation_name: string; callback_url?: string; metadata?: Record; properties?: Record; }): MockConversation { const conversationId = IdGenerator.generateConversationId(); const conversation: MockConversation = { conversation_id: conversationId, conversation_name: data.conversation_name, conversation_url: `https://tavus.daily.co/${conversationId}`, status: 'active', replica_id: data.replica_id, persona_id: data.persona_id, callback_url: data.callback_url, metadata: data.metadata, properties: data.properties, created_at: new Date().toISOString(), updated_at: new Date().toISOString(), duration_seconds: 0 }; this.conversations.set(conversation.conversation_id, conversation); logger.info(`Created conversation: ${conversation.conversation_id}`); return conversation; } static endConversation(id: string, _reason?: string): MockConversation { const conversation = this.conversations.get(id); if (!conversation) { throw new Error(`Conversation ${id} not found`); } const endedAt = new Date().toISOString(); const durationSeconds = Math.floor((new Date(endedAt).getTime() - new Date(conversation.created_at).getTime()) / 1000); const updatedConversation: MockConversation = { ...conversation, status: 'ended', ended_at: endedAt, duration_seconds: durationSeconds, updated_at: endedAt }; this.conversations.set(id, updatedConversation); logger.info(`Ended conversation: ${id}`); return updatedConversation; } static deleteConversation(id: string): boolean { const deleted = this.conversations.delete(id); if (deleted) { logger.info(`Deleted conversation: ${id}`); } return deleted; } // Replica management methods static getReplicas(): MockReplica[] { return Array.from(this.replicas.values()); } static getReplica(id: string): MockReplica | null { return this.replicas.get(id) || null; } static createReplica(data: { replica_name: string; model_name?: string }): MockReplica { const replica: MockReplica = { replica_id: IdGenerator.generateReplicaId(), replica_name: data.replica_name, status: 'pending', thumbnail_video_url: `https://cdn.replica.tavus.io/${Math.floor(Math.random() * 9999)}/${IdGenerator.generateReplicaId()}.mp4`, training_progress: '0/100', model_name: data.model_name || 'phoenix-2', created_at: new Date().toISOString(), updated_at: new Date().toISOString() }; this.replicas.set(replica.replica_id, replica); logger.info(`Created replica: ${replica.replica_id}`); return replica; } static updateReplica(replicaId: string, updates: Partial): MockReplica | null { const replica = this.replicas.get(replicaId); if (replica) { Object.assign(replica, updates, { updated_at: new Date().toISOString() }); logger.info(`Updated replica: ${replicaId}`); return replica; } return null; } static deleteReplica(replicaId: string): boolean { const deleted = this.replicas.delete(replicaId); if (deleted) { logger.info(`Deleted replica: ${replicaId}`); } return deleted; } // Persona management methods static getPersonas(): MockPersona[] { return Array.from(this.personas.values()); } static getPersona(id: string): MockPersona | null { return this.personas.get(id) || null; } static createPersona(data: { name: string; description: string; instructions: string; voice_id: string; language: string; metadata?: Record; }): MockPersona { const persona: MockPersona = { persona_id: IdGenerator.generatePersonaId(), name: data.name, description: data.description, instructions: data.instructions, voice_id: data.voice_id, language: data.language, status: 'active', metadata: data.metadata, created_at: new Date().toISOString(), updated_at: new Date().toISOString() }; this.personas.set(persona.persona_id, persona); logger.info(`Created persona: ${persona.persona_id}`); return persona; } static updatePersona(id: string, updates: Partial): MockPersona | null { const persona = this.personas.get(id); if (persona) { Object.assign(persona, updates, { updated_at: new Date().toISOString() }); logger.info(`Updated persona: ${id}`); return persona; } return null; } static deletePersona(id: string): boolean { const deleted = this.personas.delete(id); if (deleted) { logger.info(`Deleted persona: ${id}`); } return deleted; } // Video management methods static getVideos(): MockVideo[] { return Array.from(this.videos.values()); } static getVideo(id: string): MockVideo | null { return this.videos.get(id) || null; } static createVideo(data: { conversation_id: string; title: string; description?: string; format: string; quality: string; metadata?: Record; }): MockVideo { const video: MockVideo = { video_id: IdGenerator.generateVideoId(), conversation_id: data.conversation_id, title: data.title, description: data.description, format: data.format, quality: data.quality, status: 'processing', progress: 0, estimated_completion: new Date(Date.now() + 15 * 60 * 1000).toISOString(), // 15 minutes from now metadata: data.metadata, created_at: new Date().toISOString(), updated_at: new Date().toISOString() }; this.videos.set(video.video_id, video); logger.info(`Created video: ${video.video_id}`); return video; } static deleteVideo(id: string): boolean { const deleted = this.videos.delete(id); if (deleted) { logger.info(`Deleted video: ${id}`); } return deleted; } // Speech management methods static getSpeech(): MockSpeech[] { return Array.from(this.speech.values()); } static getSpeechById(id: string): MockSpeech | null { return this.speech.get(id) || null; } static createSpeech(data: { text: string; voice_id: string; language: string; speed: number; pitch: number; metadata?: Record; }): MockSpeech { const speech: MockSpeech = { speech_id: IdGenerator.generateSpeechId(), text: data.text, voice_id: data.voice_id, language: data.language, speed: data.speed, pitch: data.pitch, status: 'processing', progress: 0, estimated_completion: new Date(Date.now() + 5 * 60 * 1000).toISOString(), // 5 minutes from now metadata: data.metadata, created_at: new Date().toISOString(), updated_at: new Date().toISOString() }; this.speech.set(speech.speech_id, speech); logger.info(`Created speech: ${speech.speech_id}`); return speech; } static deleteSpeech(id: string): boolean { const deleted = this.speech.delete(id); if (deleted) { logger.info(`Deleted speech: ${id}`); } return deleted; } // Lipsync management methods static getLipsyncs(): MockLipsync[] { return Array.from(this.lipsyncs.values()); } static getLipsync(id: string): MockLipsync | null { return this.lipsyncs.get(id) || null; } static createLipsync(data: { replica_id: string; audio_url: string; title: string; description?: string; quality: string; metadata?: Record; }): MockLipsync { const lipsync: MockLipsync = { lipsync_id: IdGenerator.generateLipsyncId(), replica_id: data.replica_id, audio_url: data.audio_url, title: data.title, description: data.description, quality: data.quality, status: 'processing', progress: 0, estimated_completion: new Date(Date.now() + 20 * 60 * 1000).toISOString(), // 20 minutes from now metadata: data.metadata, created_at: new Date().toISOString(), updated_at: new Date().toISOString() }; this.lipsyncs.set(lipsync.lipsync_id, lipsync); logger.info(`Created lipsync: ${lipsync.lipsync_id}`); return lipsync; } static deleteLipsync(id: string): boolean { const deleted = this.lipsyncs.delete(id); if (deleted) { logger.info(`Deleted lipsync: ${id}`); } return deleted; } // Webhook management methods static getWebhooks(): MockWebhook[] { return Array.from(this.webhooks.values()); } static createWebhook(data: { url: string; events: string[]; secret: string; description?: string; }): MockWebhook { const webhook: MockWebhook = { webhook_id: IdGenerator.generateWebhookId(), url: data.url, events: data.events, secret: data.secret, description: data.description, status: 'active', created_at: new Date().toISOString(), updated_at: new Date().toISOString() }; this.webhooks.set(webhook.webhook_id, webhook); logger.info(`Created webhook: ${webhook.webhook_id}`); return webhook; } static deleteWebhook(id: string): boolean { const deleted = this.webhooks.delete(id); if (deleted) { logger.info(`Deleted webhook: ${id}`); } return deleted; } // Analytics methods static getUsageAnalytics(): unknown { return { period: { start: new Date(new Date().getFullYear(), new Date().getMonth(), 1).toISOString(), end: new Date().toISOString() }, usage: { conversations: { total: this.conversations.size, active: Array.from(this.conversations.values()).filter(c => c.status === 'active').length, ended: Array.from(this.conversations.values()).filter(c => c.status === 'ended').length }, videos: { total: this.videos.size, completed: Array.from(this.videos.values()).filter(v => v.status === 'completed').length, processing: Array.from(this.videos.values()).filter(v => v.status === 'processing').length }, speech: { total: this.speech.size, completed: Array.from(this.speech.values()).filter(s => s.status === 'completed').length, processing: Array.from(this.speech.values()).filter(s => s.status === 'processing').length }, lipsync: { total: this.lipsyncs.size, completed: Array.from(this.lipsyncs.values()).filter(l => l.status === 'completed').length, processing: Array.from(this.lipsyncs.values()).filter(l => l.status === 'processing').length } }, credits: { used: 475, remaining: 525, total: 1000 } }; } static getConversationAnalytics(): unknown { const conversations = Array.from(this.conversations.values()); const endedConversations = conversations.filter(c => c.status === 'ended'); const totalDuration = endedConversations.reduce((sum, c) => sum + (c.duration_seconds || 0), 0); return { period: { start: new Date(new Date().getFullYear(), new Date().getMonth(), 1).toISOString(), end: new Date().toISOString() }, conversations: { total: conversations.length, average_duration_minutes: endedConversations.length > 0 ? (totalDuration / endedConversations.length) / 60 : 0, completion_rate: conversations.length > 0 ? endedConversations.length / conversations.length : 0, by_status: { active: conversations.filter(c => c.status === 'active').length, ended: endedConversations.length }, by_replica: this.groupByReplica(conversations), by_persona: this.groupByPersona(conversations) }, trends: { daily_volume: this.generateDailyVolume(conversations) } }; } // Helper methods private static groupByReplica(conversations: MockConversation[]): Record { const groups: Record = {}; conversations.forEach(c => { groups[c.replica_id] = (groups[c.replica_id] || 0) + 1; }); return groups; } private static groupByPersona(conversations: MockConversation[]): Record { const groups: Record = {}; conversations.forEach(c => { groups[c.persona_id] = (groups[c.persona_id] || 0) + 1; }); return groups; } private static generateDailyVolume(conversations: MockConversation[]): {date: string; count: number}[] { const today = new Date(); const volume = []; for (let i = 0; i < 7; i++) { const date = new Date(today); date.setDate(date.getDate() - i); const dateStr = date.toISOString().split('T')[0]; const count = conversations.filter(c => c.created_at.startsWith(dateStr) ).length; volume.unshift({ date: dateStr, count }); } return volume; } // Default data creation private static createDefaultReplicas(): void { const realisticReplicas = [ { replica_name: 'Victoria - Selfie 2', status: 'completed' as const, thumbnail_video_url: 'https://cdn.replica.tavus.io/2913/4f309123.mp4', training_progress: '100/100', model_name: 'phoenix-2' }, { replica_name: 'Jennifer - Office', status: 'completed' as const, thumbnail_video_url: 'https://cdn.replica.tavus.io/3051/37880a60.mp4', training_progress: '100/100', model_name: 'phoenix-2' }, { replica_name: 'Diego - Blue', status: 'completed' as const, thumbnail_video_url: 'https://cdn.replica.tavus.io/3253/cac059e7.mp4', training_progress: '100/100', model_name: 'phoenix-2' }, { replica_name: 'Anna - Selfie', status: 'completed' as const, thumbnail_video_url: 'https://cdn.replica.tavus.io/3254/dac059e8.mp4', training_progress: '100/100', model_name: 'phoenix-2' }, { replica_name: 'Leonardo', status: 'completed' as const, thumbnail_video_url: 'https://cdn.replica.tavus.io/3255/eac059e9.mp4', training_progress: '100/100', model_name: 'phoenix-2' }, { replica_name: 'Eric - Aqua', status: 'completed' as const, thumbnail_video_url: 'https://cdn.replica.tavus.io/3256/fac059ea.mp4', training_progress: '100/100', model_name: 'phoenix-2' } ]; realisticReplicas.forEach(replica => { const mockReplica: MockReplica = { replica_id: IdGenerator.generateReplicaId(), replica_name: replica.replica_name, status: replica.status, thumbnail_video_url: replica.thumbnail_video_url, training_progress: replica.training_progress, model_name: replica.model_name, created_at: new Date().toISOString(), updated_at: new Date().toISOString() }; this.replicas.set(mockReplica.replica_id, mockReplica); }); } private static createDefaultPersonas(): void { const realisticPersonas = [ { name: 'Life Coach', description: 'Professional life coaching and personal development', instructions: 'You are a professional life coach with expertise in personal development, goal setting, and motivation. Help clients achieve their personal and professional goals through thoughtful guidance and actionable advice.', voice_id: 'voice_life_coach_001', language: 'en-US' }, { name: 'Doctor', description: 'Medical consultation and health advice', instructions: 'You are a medical professional providing general health information and guidance. Always recommend consulting with healthcare providers for specific medical concerns.', voice_id: 'voice_doctor_001', language: 'en-US' }, { name: 'Therapist', description: 'Mental health and counseling support', instructions: 'You are a licensed therapist providing mental health support and counseling. Offer empathetic, professional guidance while encouraging professional help for serious concerns.', voice_id: 'voice_therapist_001', language: 'en-US' }, { name: 'Mechanic', description: 'Automotive repair and maintenance advice', instructions: 'You are an experienced automotive mechanic. Provide practical advice on car maintenance, troubleshooting, and repair procedures.', voice_id: 'voice_mechanic_001', language: 'en-US' }, { name: 'Personal Trainer', description: 'Fitness training and workout guidance', instructions: 'You are a certified personal trainer. Help clients with workout plans, exercise form, and fitness motivation.', voice_id: 'voice_trainer_001', language: 'en-US' }, { name: 'Tutor', description: 'Educational support and academic assistance', instructions: 'You are an experienced tutor. Help students understand complex topics, improve study skills, and achieve academic success.', voice_id: 'voice_tutor_001', language: 'en-US' } ]; realisticPersonas.forEach(persona => { const mockPersona: MockPersona = { persona_id: IdGenerator.generatePersonaId(), name: persona.name, description: persona.description, instructions: persona.instructions, voice_id: persona.voice_id, language: persona.language, status: 'active', created_at: new Date().toISOString(), updated_at: new Date().toISOString() }; this.personas.set(mockPersona.persona_id, mockPersona); }); } private static createDefaultConversations(): void { // Create a few sample conversations for testing const realisticConversations = [ { replica_id: Array.from(this.replicas.keys())[0], persona_id: Array.from(this.personas.keys())[0], conversation_name: 'A Meeting with Victoria', status: 'ended' as const }, { replica_id: Array.from(this.replicas.keys())[1], persona_id: Array.from(this.personas.keys())[1], conversation_name: 'Health Consultation with Dr. Jennifer', status: 'active' as const }, { replica_id: Array.from(this.replicas.keys())[2], persona_id: Array.from(this.personas.keys())[2], conversation_name: 'Therapy Session with Diego', status: 'ended' as const } ]; realisticConversations.forEach((conv, index) => { const conversationId = IdGenerator.generateConversationId(); const conversation: MockConversation = { conversation_id: conversationId, conversation_name: conv.conversation_name, conversation_url: `https://tavus.daily.co/${conversationId}`, status: conv.status, replica_id: conv.replica_id, persona_id: conv.persona_id, created_at: new Date(Date.now() - (index * 24 * 60 * 60 * 1000)).toISOString(), // Different dates updated_at: new Date().toISOString(), duration_seconds: conv.status === 'ended' ? 1800 : 0 }; if (conv.status === 'ended') { conversation.ended_at = new Date(Date.now() - (index * 60 * 60 * 1000)).toISOString(); } this.conversations.set(conversation.conversation_id, conversation); }); } // Objectives methods static getObjectives(): unknown[] { return this.objectives; } static getObjective(id: string): unknown | null { return this.objectives.find(obj => obj.uuid === id) || null; } // Guardrails methods static getGuardrails(): unknown[] { return this.guardrails; } static getGuardrail(id: string): unknown | null { return this.guardrails.find(g => g.uuid === id) || null; } static getStats(): unknown { return { conversations: this.conversations.size, replicas: this.replicas.size, personas: this.personas.size, videos: this.videos.size, speech: this.speech.size, lipsyncs: this.lipsyncs.size, webhooks: this.webhooks.size, objectives: this.objectives.length, guardrails: this.guardrails.length }; } }