'use strict';

function sanitizeText(text, maxLength = 80) {
    if (!text || text.trim().length === 0)
        return "";
    let sanitized = text.trim();
    // Remove common PII patterns
    // Email addresses
    sanitized = sanitized.replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g, "[EMAIL]");
    // Phone numbers (various formats)
    sanitized = sanitized.replace(/\b\d{3}[-.]?\d{3}[-.]?\d{4}\b/g, "[PHONE]");
    sanitized = sanitized.replace(/\b\(\d{3}\)\s*\d{3}[-.]?\d{4}\b/g, "[PHONE]");
    sanitized = sanitized.replace(/\+\d{1,3}[-\s.]?\d{1,4}[-\s.]?\d{1,4}[-\s.]?\d{1,9}/g, "[PHONE]");
    // Credit card numbers (groups of 4 digits)
    sanitized = sanitized.replace(/\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g, "[CARD]");
    // SSN patterns
    sanitized = sanitized.replace(/\b\d{3}-\d{2}-\d{4}\b/g, "[SSN]");
    // IP addresses
    sanitized = sanitized.replace(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g, "[IP]");
    // URLs
    sanitized = sanitized.replace(/https?:\/\/[^\s]+/g, "[URL]");
    // Truncate to max length with ellipsis if needed
    if (sanitized.length > maxLength) {
        sanitized = sanitized.substring(0, maxLength - 3) + "...";
    }
    return sanitized;
}
class GoogleAnalyticsProvider {
    isAvailable() {
        return typeof window !== "undefined" && (typeof window["gtag"] === "function" || typeof window["dataLayer"] !== "undefined");
    }
    trackEvent(eventName, params) {
        if (!this.isAvailable()) {
            console.warn("Google Analytics is not available. Event not sent:", eventName);
            return;
        }
        try {
            // Sanitize questionText to remove PII and truncate to GA4 limits
            const sanitizedQuestion = sanitizeText(params.questionText || "");
            // Support both gtag and GTM dataLayer approaches
            if (typeof window["gtag"] === "function") {
                // Direct GA4 gtag approach
                window["gtag"]("event", eventName, Object.assign({ conversation_id: params.conversationId, feedback_type: params.feedback, agent_id: params.agentId, question_text: sanitizedQuestion, answer_id: params.answerId || "", timestamp: params.timestamp, environment: params.env }, this.getCustomParams(params)));
            }
            else if (window["dataLayer"]) {
                // Google Tag Manager dataLayer approach
                window["dataLayer"].push(Object.assign({ event: eventName, conversation_id: params.conversationId, feedback_type: params.feedback, agent_id: params.agentId, question_text: sanitizedQuestion, answer_id: params.answerId || "", timestamp: params.timestamp, environment: params.env }, this.getCustomParams(params)));
            }
        }
        catch (error) {
            console.error("Error sending analytics event:", error);
        }
    }
    getCustomParams(params) {
        const standardKeys = ["conversationId", "feedback", "agentId", "projectId", "questionText", "answerId", "answerText", "timestamp", "env"];
        const customParams = {};
        Object.keys(params).forEach(key => {
            if (!standardKeys.includes(key)) {
                customParams[key] = params[key];
            }
        });
        return customParams;
    }
}
class ConsoleLoggerProvider {
    isAvailable() {
        return typeof console !== "undefined";
    }
    trackEvent(eventName, params) {
        console.log(`[Analytics Debug] Event: ${eventName}`, params);
    }
}
class AnalyticsService {
    constructor() {
        this.providers = [];
        this.feedbackCache = new Set(); // For idempotency
        // Initialize with Google Analytics provider
        this.providers.push(new GoogleAnalyticsProvider());
        // Add console logger in non-production environments
        if (typeof window !== "undefined" && window.location.hostname === "localhost") {
            this.providers.push(new ConsoleLoggerProvider());
        }
    }
    static getInstance() {
        if (!AnalyticsService.instance) {
            AnalyticsService.instance = new AnalyticsService();
        }
        return AnalyticsService.instance;
    }
    registerProvider(provider) {
        this.providers.push(provider);
    }
    trackFeedback(params) {
        // Validate required parameters
        if (!params.conversationId) {
            console.warn("[Analytics] Cannot send feedback event: conversationId is required");
            return;
        }
        if (!params.feedback || !["up", "down"].includes(params.feedback)) {
            console.warn("[Analytics] Cannot send feedback event: feedback must be 'up' or 'down'");
            return;
        }
        // Generate idempotency key
        const idempotencyKey = this.generateIdempotencyKey(params);
        // Check if this exact feedback was already sent
        if (this.feedbackCache.has(idempotencyKey)) {
            console.log("[Analytics] Duplicate feedback event prevented:", idempotencyKey);
            return;
        }
        // Add to cache
        this.feedbackCache.add(idempotencyKey);
        // Track event with all available providers
        const eventName = "ai12z_feedback";
        this.providers.forEach(provider => {
            if (provider.isAvailable()) {
                try {
                    provider.trackEvent(eventName, params);
                }
                catch (error) {
                    console.error("Error in analytics provider:", error);
                }
            }
        });
        // Clean up old cache entries after 5 minutes to prevent memory leaks
        setTimeout(() => {
            this.feedbackCache.delete(idempotencyKey);
        }, 5 * 60 * 1000);
    }
    changeFeedback(oldParams, newParams) {
        const oldKey = this.generateIdempotencyKey(oldParams);
        this.feedbackCache.delete(oldKey);
        this.trackFeedback(newParams);
    }
    generateIdempotencyKey(params) {
        return `${params.conversationId}_${params.answerId || params.timestamp}_${params.feedback}`;
    }
    clearCache() {
        this.feedbackCache.clear();
    }
}
function getEnvironment(mode) {
    switch (mode) {
        case "local":
            return "local";
        case "dev":
            return "dev";
        case "staging":
            return "staging";
        default:
            return "prod";
    }
}
function getQuestionText(chatHistory, answerId) {
    if (!chatHistory || chatHistory.length === 0)
        return "";
    // Find the user message that precedes the AI response with the given answerId
    for (let i = chatHistory.length - 1; i >= 0; i--) {
        const message = chatHistory[i];
        if (message.id === answerId || message.insightId === answerId) {
            // Found the AI message, now look for the preceding user message
            for (let j = i - 1; j >= 0; j--) {
                if (chatHistory[j].type === "user") {
                    return chatHistory[j].message || "";
                }
            }
        }
    }
    // If no specific answerId, return the last user message
    for (let i = chatHistory.length - 1; i >= 0; i--) {
        if (chatHistory[i].type === "user") {
            return chatHistory[i].message || "";
        }
    }
    return "";
}
function trackFeedbackAnalytics(feedback, answerId, payload, conversationIdFallback) {
    const analytics = AnalyticsService.getInstance();
    analytics.trackFeedback({
        conversationId: payload.conversationId || conversationIdFallback || answerId || "unknown",
        feedback: feedback,
        agentId: payload.projectId || "unknown",
        questionText: payload.questionText || "",
        answerId: answerId || "unknown",
        timestamp: new Date().toISOString(),
        env: getEnvironment(payload.dataMode),
    });
}

exports.getQuestionText = getQuestionText;
exports.trackFeedbackAnalytics = trackFeedbackAnalytics;
