import PostHog from "posthog-react-native"; import { Platform } from "react-native"; import type { OperoChatError, OperoChatMessage } from "../types"; import { log } from "../utils/helpers"; export interface OperoAnalyticsConfig { enableInDevelopment?: boolean; } export interface APICallContext { endpoint: string; method: string; duration: number; success: boolean; statusCode: number; errorType?: string; retryAttempt?: number; } export interface ErrorContext { userEmail?: string; conversationId?: string; messageCount: number; apiEndpoint: string; lastAPICall?: string; apiResponseTime?: number; customStylesEnabled: boolean; filtersActive: boolean; errorSequence?: string[]; retryAttempted?: boolean; networkStatus?: "online" | "offline"; } export interface SessionMetrics { durationMs: number; messageCount: number; apiCalls: number; errorsEncountered: number; featuresUsed: string[]; } export class OperoAnalyticsService { private posthog: PostHog | null = null; private sessionStartTime?: Date; private sessionMetrics: SessionMetrics = { durationMs: 0, messageCount: 0, apiCalls: 0, errorsEncountered: 0, featuresUsed: [], }; // Centralized PostHog configuration - baked into SDK private static readonly POSTHOG_CONFIG = { apiKey: "phc_KqbddeD5cZeDGoaYtQfd4bMDf9QfUtf9HQ57636DM4c", // Safe to share host: "https://eu.i.posthog.com", }; constructor( userEmail?: string, userRole?: string, config: OperoAnalyticsConfig = {}, ) { // Always initialize unless in development without explicit enablement const isDevelopment = __DEV__; const shouldInitialize = !isDevelopment || config.enableInDevelopment === true; if (shouldInitialize) { try { this.posthog = new PostHog( OperoAnalyticsService.POSTHOG_CONFIG.apiKey, { host: OperoAnalyticsService.POSTHOG_CONFIG.host, enableSessionReplay: true, sessionReplayConfig: { maskAllTextInputs: false, maskAllImages: false, maskAllSandboxedViews: false, captureLog: true, captureNetworkTelemetry: true, }, }, ); // Identify user immediately if email provided if (userEmail) { this.identifyUser(userEmail, userRole); } log("Analytics service initialized successfully", "info"); } catch (error) { log("Failed to initialize analytics service", "error"); console.error("Analytics initialization error:", error); } } else { log("Analytics disabled in development mode", "info"); } } private identifyUser(userEmail: string, userRole?: string): void { if (!this.posthog) return; try { this.posthog.identify(userEmail, { email: userEmail, role: userRole || null, platform: Platform.OS, platform_version: Platform.Version, is_development: __DEV__, }); } catch (error) { log("Failed to identify user in analytics", "error"); } } // SDK Lifecycle Events trackSDKInitialized(config: { hasCustomStyles: boolean; hasFilters: boolean; apiEndpoint: string; callbacksConfigured: string[]; }): void { if (!this.posthog) return; this.sessionStartTime = new Date(); this.sessionMetrics = { durationMs: 0, messageCount: 0, apiCalls: 0, errorsEncountered: 0, featuresUsed: [], }; try { this.posthog.capture("sdk_initialized", { has_custom_styles: config.hasCustomStyles, has_filters: config.hasFilters, api_endpoint: config.apiEndpoint, callbacks_configured: config.callbacksConfigured, platform: Platform.OS, }); // Track features configured if (config.hasCustomStyles) this.sessionMetrics.featuresUsed.push("custom_styles"); if (config.hasFilters) this.sessionMetrics.featuresUsed.push("filters"); if (config.callbacksConfigured.length > 0) this.sessionMetrics.featuresUsed.push("callbacks"); } catch (error) { log("Failed to track SDK initialization", "error"); } } // Chat Engagement Events trackChatSessionStarted(): void { if (!this.posthog) return; try { this.posthog.capture("chat_session_started", { timestamp: new Date().toISOString(), }); } catch (error) { log("Failed to track chat session start", "error"); } } trackChatSessionEnded(): void { if (!this.posthog || !this.sessionStartTime) return; try { const sessionDuration = Date.now() - this.sessionStartTime.getTime(); this.sessionMetrics.durationMs = sessionDuration; this.posthog.capture("chat_session_ended", { session_duration_ms: sessionDuration, session_duration_minutes: Math.round(sessionDuration / 60000), messages_sent: this.sessionMetrics.messageCount, api_calls_made: this.sessionMetrics.apiCalls, errors_encountered: this.sessionMetrics.errorsEncountered, features_used: this.sessionMetrics.featuresUsed, }); } catch (error) { log("Failed to track chat session end", "error"); } } trackMessageSent(messageLength: number, hasFilters: boolean): void { if (!this.posthog) return; this.sessionMetrics.messageCount++; try { this.posthog.capture("message_sent", { message_length: messageLength, has_filters: hasFilters, message_number: this.sessionMetrics.messageCount, }); if (hasFilters && !this.sessionMetrics.featuresUsed.includes("filters")) { this.sessionMetrics.featuresUsed.push("filters"); } } catch (error) { log("Failed to track message sent", "error"); } } trackStreamingStarted(): void { if (!this.posthog) return; try { this.posthog.capture("streaming_started", { timestamp: new Date().toISOString(), }); } catch (error) { log("Failed to track streaming start", "error"); } } trackStreamingCompleted(durationMs: number, messageLength?: number): void { if (!this.posthog) return; try { this.posthog.capture("streaming_completed", { duration_ms: durationMs, message_length: messageLength || 0, }); } catch (error) { log("Failed to track streaming completion", "error"); } } // Feature Usage Events trackSampleQuestionClicked(question: string, questionIndex: number): void { if (!this.posthog) return; try { this.posthog.capture("sample_question_clicked", { question_text: question, question_index: questionIndex, }); if (!this.sessionMetrics.featuresUsed.includes("sample_questions")) { this.sessionMetrics.featuresUsed.push("sample_questions"); } } catch (error) { log("Failed to track sample question click", "error"); } } trackSampleQuestionsDisplayed(questionCount: number): void { if (!this.posthog) return; try { this.posthog.capture("sample_questions_displayed", { question_count: questionCount, }); } catch (error) { log("Failed to track sample questions display", "error"); } } trackSourcesViewed(sourcesCount: number): void { if (!this.posthog) return; try { this.posthog.capture("sources_viewed", { sources_count: sourcesCount, }); if (!this.sessionMetrics.featuresUsed.includes("sources")) { this.sessionMetrics.featuresUsed.push("sources"); } } catch (error) { log("Failed to track sources view", "error"); } } trackFiltersApplied(filterTypes: string[], documentCount: number): void { if (!this.posthog) return; try { this.posthog.capture("filters_applied", { filter_types: filterTypes, document_count: documentCount, }); if (!this.sessionMetrics.featuresUsed.includes("filters")) { this.sessionMetrics.featuresUsed.push("filters"); } } catch (error) { log("Failed to track filters applied", "error"); } } trackMessageReaction(reactionType: string, messageId: string): void { if (!this.posthog) return; try { this.posthog.capture("message_reaction", { reaction_type: reactionType, message_id: messageId, }); if (!this.sessionMetrics.featuresUsed.includes("reactions")) { this.sessionMetrics.featuresUsed.push("reactions"); } } catch (error) { log("Failed to track message reaction", "error"); } } // API Performance Tracking trackAPICall(context: APICallContext): void { if (!this.posthog) return; this.sessionMetrics.apiCalls++; try { this.posthog.capture("api_call", { endpoint: context.endpoint, method: context.method, duration_ms: context.duration, success: context.success, status_code: context.statusCode, error_type: context.errorType || null, retry_attempt: context.retryAttempt || 0, }); // Track performance metrics if (context.duration > 5000) { this.posthog.capture("slow_api_call", { endpoint: context.endpoint, duration_ms: context.duration, }); } } catch (error) { log("Failed to track API call", "error"); } } trackConnectivityCheck(success: boolean, duration: number): void { if (!this.posthog) return; try { this.posthog.capture("connectivity_check", { success, duration_ms: duration, }); } catch (error) { log("Failed to track connectivity check", "error"); } } // Error Tracking trackError(error: OperoChatError, context: ErrorContext): void { if (!this.posthog) return; this.sessionMetrics.errorsEncountered++; try { this.posthog.capture("error_occurred", { error_type: error.type, error_message: error.message, error_persistent: error.persistent || false, ...context, session_errors_count: this.sessionMetrics.errorsEncountered, }); // Track specific error types for analysis if (error.type === "api") { this.posthog.capture("api_error", { error_message: error.message, api_endpoint: context.apiEndpoint, last_api_call: context.lastAPICall || null, }); } } catch (trackingError) { log("Failed to track error", "error"); } } // Session Replay Controls startSessionReplay(): void { if (!this.posthog) return; try { // PostHog React Native automatically handles session replay // This method is for explicit control if needed log("Session replay is active", "info"); } catch (error) { log("Failed to start session replay", "error"); } } stopSessionReplay(): void { if (!this.posthog) return; try { // PostHog React Native automatically handles session replay // This method is for explicit control if needed log("Session replay stopped", "info"); } catch (error) { log("Failed to stop session replay", "error"); } } // Business Metrics trackConversationMetrics(messages: OperoChatMessage[]): void { if (!this.posthog || messages.length === 0) return; try { const userMessages = messages.filter((m) => m.role === "user"); const assistantMessages = messages.filter((m) => m.role === "assistant"); const averageMessageLength = userMessages.reduce((sum, m) => sum + m.content.length, 0) / userMessages.length; const conversationDuration = messages.length > 1 ? new Date(messages[messages.length - 1]!.timestamp).getTime() - new Date(messages[0]!.timestamp).getTime() : 0; this.posthog.capture("conversation_metrics", { total_messages: messages.length, user_messages: userMessages.length, assistant_messages: assistantMessages.length, average_message_length: Math.round(averageMessageLength), conversation_duration_ms: conversationDuration, conversation_duration_minutes: Math.round(conversationDuration / 60000), has_sources: assistantMessages.some( (m) => m.sources && m.sources.length > 0, ), has_filters: assistantMessages.some((m) => m.hasFilters), }); } catch (error) { log("Failed to track conversation metrics", "error"); } } // Cleanup cleanup(): void { if (this.sessionStartTime) { this.trackChatSessionEnded(); } // PostHog cleanup is handled automatically this.posthog = null; } }