// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
import * as os from 'node:os';
import * as path from 'node:path';
import { FileSystem, JsonFile } from '@rushstack/node-core-library';
import { Rush } from '../api/Rush';
import { collectPerformanceEntries } from '../utilities/performance';
const MAX_FILE_COUNT = 100;
const ONE_MEGABYTE_IN_BYTES = 1048576;
export class Telemetry {
    constructor(rushConfiguration, rushSession) {
        this._flushAsyncTasks = new Set();
        this._telemetryStartTime = 0;
        this._rushConfiguration = rushConfiguration;
        this._rushSession = rushSession;
        this._enabled = this._rushConfiguration.telemetryEnabled;
        this._store = [];
        const folderName = 'telemetry';
        this._dataFolder = path.join(this._rushConfiguration.commonTempFolder, folderName);
    }
    log(telemetryData) {
        if (!this._enabled) {
            return;
        }
        const cpus = os.cpus();
        const data = {
            ...telemetryData,
            performanceEntries: telemetryData.performanceEntries || collectPerformanceEntries(this._telemetryStartTime),
            machineInfo: telemetryData.machineInfo || {
                machineArchitecture: os.arch(),
                // The Node.js model is sometimes padded, for example:
                // "AMD Ryzen 7 3700X 8-Core Processor             "
                machineCpu: cpus[0].model.trim(),
                machineCores: cpus.length,
                machineTotalMemoryMiB: Math.round(os.totalmem() / ONE_MEGABYTE_IN_BYTES),
                machineFreeMemoryMiB: Math.round(os.freemem() / ONE_MEGABYTE_IN_BYTES)
            },
            timestampMs: telemetryData.timestampMs || new Date().getTime(),
            platform: telemetryData.platform || process.platform,
            rushVersion: telemetryData.rushVersion || Rush.version
        };
        this._telemetryStartTime = performance.now();
        this._store.push(data);
    }
    flush() {
        if (!this._enabled || this._store.length === 0) {
            return;
        }
        const fullPath = this._getFilePath();
        JsonFile.save(this._store, fullPath, { ensureFolderExists: true, ignoreUndefinedValues: true });
        if (this._rushSession.hooks.flushTelemetry.isUsed()) {
            /**
             * User defined flushTelemetry should not block anything, so we don't await here,
             * and store the promise into a list so that we can await it later.
             */
            const asyncTaskPromise = this._rushSession.hooks.flushTelemetry.promise(this._store);
            this._flushAsyncTasks.add(asyncTaskPromise);
            asyncTaskPromise.then(() => {
                this._flushAsyncTasks.delete(asyncTaskPromise);
            }, () => {
                this._flushAsyncTasks.delete(asyncTaskPromise);
            });
        }
        this._store = [];
        this._cleanUp();
    }
    /**
     * There are some async tasks that are not finished when the process is exiting.
     */
    async ensureFlushedAsync() {
        await Promise.all(this._flushAsyncTasks);
    }
    get store() {
        return this._store;
    }
    /**
     * When there are too many log files, delete the old ones.
     */
    _cleanUp() {
        if (FileSystem.exists(this._dataFolder)) {
            const files = FileSystem.readFolderItemNames(this._dataFolder);
            if (files.length > MAX_FILE_COUNT) {
                const sortedFiles = files
                    .map((fileName) => {
                    const filePath = path.join(this._dataFolder, fileName);
                    const stats = FileSystem.getStatistics(filePath);
                    return {
                        filePath: filePath,
                        modifiedTime: stats.mtime.getTime(),
                        isFile: stats.isFile()
                    };
                })
                    .filter((value) => {
                    // Only delete files
                    return value.isFile;
                })
                    .sort((a, b) => {
                    return a.modifiedTime - b.modifiedTime;
                })
                    .map((s) => {
                    return s.filePath;
                });
                const filesToDelete = sortedFiles.length - MAX_FILE_COUNT;
                for (let i = 0; i < filesToDelete; i++) {
                    FileSystem.deleteFile(sortedFiles[i]);
                }
            }
        }
    }
    _getFilePath() {
        let fileName = `telemetry_${new Date().toISOString()}`;
        fileName = fileName.replace(/[\-\:\.]/g, '_') + '.json';
        return path.join(this._dataFolder, fileName);
    }
}
//# sourceMappingURL=Telemetry.js.map