"use strict";
/**
 * 📊 FAF CLI Analytics & Telemetry System
 * F1-inspired performance monitoring and user analytics
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.analytics = exports.FafAnalytics = void 0;
exports.trackCommand = trackCommand;
exports.trackError = trackError;
exports.trackPerformance = trackPerformance;
exports.trackFeatureUsage = trackFeatureUsage;
exports.withPerformanceTracking = withPerformanceTracking;
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const fs = __importStar(require("fs/promises"));
const championship_style_1 = require("../utils/championship-style");
// Telemetry configuration
const TELEMETRY_ENABLED = process.env.FAF_TELEMETRY !== 'false';
const TELEMETRY_ENDPOINT = 'https://telemetry.faf.one/v1/events';
const SESSION_ID = generateSessionId();
/**
 * Core Analytics Engine
 */
class FafAnalytics {
    static instance;
    events = [];
    statsPath;
    constructor() {
        this.statsPath = path.join(os.homedir(), '.faf', 'usage-stats.json');
    }
    static getInstance() {
        if (!FafAnalytics.instance) {
            FafAnalytics.instance = new FafAnalytics();
        }
        return FafAnalytics.instance;
    }
    /**
     * Track command execution
     */
    async trackCommand(command, args, duration, success) {
        if (!TELEMETRY_ENABLED) {
            return;
        }
        const event = {
            event: 'command_executed',
            timestamp: new Date().toISOString(),
            sessionId: SESSION_ID,
            version: await this.getVersion(),
            platform: this.getPlatformInfo(),
            properties: {
                command,
                args: args.filter(arg => !arg.includes('key') && !arg.includes('token')), // Security: filter sensitive args
                success,
                projectType: await this.detectProjectType()
            },
            performance: {
                duration,
                memory: process.memoryUsage(),
                cpu: this.getCpuInfo()
            }
        };
        await this.recordEvent(event);
        await this.updateUsageStats(command, duration, success);
    }
    /**
     * Track errors with context
     */
    async trackError(error, command, args) {
        if (!TELEMETRY_ENABLED) {
            return;
        }
        const event = {
            event: 'error_occurred',
            timestamp: new Date().toISOString(),
            sessionId: SESSION_ID,
            version: await this.getVersion(),
            platform: this.getPlatformInfo(),
            properties: {
                command,
                projectType: await this.detectProjectType()
            },
            error: {
                name: error.name,
                message: error.message,
                stack: error.stack,
                command,
                args: args?.filter(arg => !arg.includes('key') && !arg.includes('token'))
            }
        };
        await this.recordEvent(event);
    }
    /**
     * Track performance milestones
     */
    async trackPerformance(milestone, duration, metadata) {
        if (!TELEMETRY_ENABLED) {
            return;
        }
        const event = {
            event: 'performance_milestone',
            timestamp: new Date().toISOString(),
            sessionId: SESSION_ID,
            version: await this.getVersion(),
            platform: this.getPlatformInfo(),
            properties: {
                milestone,
                ...metadata
            },
            performance: {
                duration,
                memory: process.memoryUsage()
            }
        };
        await this.recordEvent(event);
    }
    /**
     * Track feature usage
     */
    async trackFeatureUsage(feature, context) {
        if (!TELEMETRY_ENABLED) {
            return;
        }
        const event = {
            event: 'feature_used',
            timestamp: new Date().toISOString(),
            sessionId: SESSION_ID,
            version: await this.getVersion(),
            platform: this.getPlatformInfo(),
            properties: {
                feature,
                ...context
            }
        };
        await this.recordEvent(event);
    }
    /**
     * Get usage statistics
     */
    async getUsageStats() {
        try {
            const content = await fs.readFile(this.statsPath, 'utf-8');
            return JSON.parse(content);
        }
        catch {
            return {
                totalCommands: 0,
                favoriteCommands: {},
                averageExecutionTime: 0,
                errorRate: 0,
                lastUsed: new Date().toISOString(),
                projectTypes: {}
            };
        }
    }
    /**
     * Display championship-style analytics summary
     */
    async showAnalyticsSummary() {
        const stats = await this.getUsageStats();
        console.log(`${championship_style_1.FAF_COLORS.fafCyan('📊 FAF CLI Analytics Summary')}`);
        console.log(`${championship_style_1.FAF_COLORS.fafCyan('├─')} Total commands: ${championship_style_1.FAF_COLORS.fafGreen(stats.totalCommands.toString())}`);
        console.log(`${championship_style_1.FAF_COLORS.fafCyan('├─')} Average execution: ${championship_style_1.FAF_COLORS.fafGreen(stats.averageExecutionTime.toFixed(0))}ms`);
        console.log(`${championship_style_1.FAF_COLORS.fafCyan('├─')} Error rate: ${this.formatErrorRate(stats.errorRate)}`);
        console.log(`${championship_style_1.FAF_COLORS.fafCyan('└─')} Last used: ${championship_style_1.FAF_COLORS.fafGreen(new Date(stats.lastUsed).toLocaleDateString())}`);
        if (Object.keys(stats.favoriteCommands).length > 0) {
            console.log();
            console.log(`${championship_style_1.FAF_COLORS.fafCyan('🏆 Top Commands:')}`);
            const topCommands = Object.entries(stats.favoriteCommands)
                .sort(([, a], [, b]) => b - a)
                .slice(0, 3);
            topCommands.forEach(([command, count], index) => {
                const medal = ['🥇', '🥈', '🥉'][index];
                console.log(`${championship_style_1.FAF_COLORS.fafCyan('   ')}${medal} ${command}: ${count} times`);
            });
        }
    }
    /**
     * Privacy controls
     */
    async disableTelemetry() {
        process.env.FAF_TELEMETRY = 'false';
        console.log(`${championship_style_1.FAF_COLORS.fafGreen('☑️')} Telemetry disabled. Analytics collection stopped.`);
        console.log(`${championship_style_1.FAF_COLORS.fafCyan('💡')} Re-enable with: ${championship_style_1.FAF_COLORS.fafOrange('export FAF_TELEMETRY=true')}`);
    }
    async enableTelemetry() {
        process.env.FAF_TELEMETRY = 'true';
        console.log(`${championship_style_1.FAF_COLORS.fafGreen('☑️')} Telemetry enabled. Helping improve FAF for everyone!`);
        console.log(`${championship_style_1.FAF_COLORS.fafCyan('🔒')} All data is anonymized and secure.`);
    }
    // =====================================
    // PRIVATE METHODS
    // =====================================
    async recordEvent(event) {
        this.events.push(event);
        // Batch send events (or queue for later if offline)
        if (this.events.length >= 10) {
            await this.flushEvents();
        }
    }
    async flushEvents() {
        if (this.events.length === 0) {
            return;
        }
        try {
            // In production, this would send to telemetry endpoint
            // For now, we'll just clear the events
            this.events = [];
        }
        catch {
            // Silent fail - telemetry should never break the CLI
        }
    }
    async updateUsageStats(command, duration, success) {
        const stats = await this.getUsageStats();
        stats.totalCommands++;
        stats.favoriteCommands[command] = (stats.favoriteCommands[command] || 0) + 1;
        stats.averageExecutionTime = (stats.averageExecutionTime * (stats.totalCommands - 1) + duration) / stats.totalCommands;
        stats.lastUsed = new Date().toISOString();
        if (!success) {
            stats.errorRate = (stats.errorRate * (stats.totalCommands - 1) + 1) / stats.totalCommands;
        }
        else {
            stats.errorRate = (stats.errorRate * (stats.totalCommands - 1)) / stats.totalCommands;
        }
        const projectType = await this.detectProjectType();
        if (projectType) {
            stats.projectTypes[projectType] = (stats.projectTypes[projectType] || 0) + 1;
        }
        await this.saveUsageStats(stats);
    }
    async saveUsageStats(stats) {
        try {
            await fs.mkdir(path.dirname(this.statsPath), { recursive: true });
            await fs.writeFile(this.statsPath, JSON.stringify(stats, null, 2));
        }
        catch {
            // Silent fail
        }
    }
    async getVersion() {
        try {
            const packagePath = path.join(__dirname, '../../package.json');
            const content = await fs.readFile(packagePath, 'utf-8');
            const pkg = JSON.parse(content);
            return pkg.version;
        }
        catch {
            return 'unknown';
        }
    }
    getPlatformInfo() {
        return `${os.platform()}-${os.arch()}-node${process.version}`;
    }
    getCpuInfo() {
        const cpus = os.cpus();
        return {
            model: cpus[0]?.model || 'unknown',
            speed: cpus[0]?.speed || 0,
            cores: cpus.length
        };
    }
    async detectProjectType() {
        try {
            const cwd = process.cwd();
            const files = await fs.readdir(cwd);
            if (files.includes('package.json')) {
                return 'nodejs';
            }
            if (files.includes('requirements.txt') || files.includes('pyproject.toml')) {
                return 'python';
            }
            if (files.includes('Cargo.toml')) {
                return 'rust';
            }
            if (files.includes('go.mod')) {
                return 'golang';
            }
            if (files.includes('pom.xml') || files.includes('build.gradle')) {
                return 'java';
            }
            return null;
        }
        catch {
            return null;
        }
    }
    formatErrorRate(rate) {
        const percentage = (rate * 100).toFixed(1);
        const color = rate < 0.05 ? championship_style_1.FAF_COLORS.fafGreen :
            rate < 0.15 ? championship_style_1.FAF_COLORS.fafOrange : championship_style_1.FAF_COLORS.fafOrange;
        return color(`${percentage}%`);
    }
}
exports.FafAnalytics = FafAnalytics;
/**
 * Convenience functions for analytics tracking
 */
exports.analytics = FafAnalytics.getInstance();
function trackCommand(command, args, duration, success) {
    return exports.analytics.trackCommand(command, args, duration, success);
}
function trackError(error, command, args) {
    return exports.analytics.trackError(error, command, args);
}
function trackPerformance(milestone, duration, metadata) {
    return exports.analytics.trackPerformance(milestone, duration, metadata);
}
function trackFeatureUsage(feature, context) {
    return exports.analytics.trackFeatureUsage(feature, context);
}
/**
 * Utility functions
 */
function generateSessionId() {
    return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
}
/**
 * Performance monitoring decorator
 */
function withPerformanceTracking(fn, name) {
    return (async (...args) => {
        const start = Date.now();
        try {
            const result = await fn(...args);
            const duration = Date.now() - start;
            await trackPerformance(name, duration, { success: true });
            return result;
        }
        catch (error) {
            const duration = Date.now() - start;
            await trackPerformance(name, duration, { success: false });
            await trackError(error, name);
            throw error;
        }
    });
}
//# sourceMappingURL=analytics.js.map