import { OneDsTelemetryProvider, ScenarioResults, TelemetryEventNames, } from '@microsoft/power-apps-common/telemetry';
import { getScrubbedCustomDimensions } from './Scrubber/ScrubCustomDimensions.js';
function regionToClusterCategory(region) {
    switch (region) {
        case 'preview':
            return 'prod';
        case 'gccmoderate':
            return 'gov';
        case 'gcchigh':
            return 'high';
        default:
            return region;
    }
}
export class OneDSWriter {
    _provider;
    _sequenceNumber = 1;
    constructor(sessionId, region, telemetryLocation, environmentId, appId, geoLocation, cliVersion, cliSource) {
        const commonProperties = {
            environmentId,
            isOnePlayer: 'false',
            webPlayerScenario: 'CodeApp_CLI_Authoring',
            cloud: region === 'preview' ? 'prod' : region,
            sessionStartTime: new Date().toISOString(),
            station: 'Unknown',
            telemetryLocation,
            cliVersion,
            cliSource,
        };
        if (appId) {
            commonProperties.playerAppId = `/providers/Microsoft.PowerApps/apps/${appId}`;
        }
        if (geoLocation) {
            commonProperties.geoLocation = geoLocation;
        }
        this._provider = new OneDsTelemetryProvider({
            clientType: cliSource === 'pac-cli' ? 'PacCLI' : 'NodeCLI',
            clusterCategory: regionToClusterCategory(region),
            telemetryLocation,
            commonProperties,
            propertyColumnMap: {
                latencyInMs: 'duration',
                elapsedTime: 'duration',
                updateCadence: 'updateCadence',
                requestedUrl: 'url',
                status: 'httpStatus',
                statusCode: 'httpStatus',
            },
            channelConfig: {
                maxEvtPerBatch: 500,
                maxEventRetryAttempts: 6,
                eventsLimitInMem: 10000,
            },
        });
        this._provider.sessionId = sessionId;
        // Sync 1DS session id with CLI session id in Part A extension
        this._provider.addTelemetryInitializer((envelope) => {
            const ext = (envelope.ext = envelope.ext ?? {});
            const app = (ext.app = ext.app ?? {});
            app.sesId = sessionId;
        });
    }
    trackActivityEvent(operationName, eventData) {
        this._trackEvent(TelemetryEventNames.Activity, {
            ...eventData,
            operationName,
        });
    }
    trackErrorEvent(operationName, eventData) {
        this._trackEvent(TelemetryEventNames.Error, {
            ...eventData,
            operationName,
        });
    }
    startScenario(scenarioName, startData) {
        this._trackEvent(TelemetryEventNames.StartScenario, {
            operationName: scenarioName,
            ...startData,
            scenarioName,
        });
    }
    completeScenario(scenarioName, completeData) {
        this._trackEvent(TelemetryEventNames.EndScenario, {
            operationName: scenarioName,
            ...completeData,
            scenarioName,
            scenarioResult: ScenarioResults.Success,
        });
    }
    scenarioFailed(scenarioName, failureData) {
        this._trackEvent(TelemetryEventNames.EndScenario, {
            operationName: scenarioName,
            ...failureData,
            scenarioName,
            scenarioResult: ScenarioResults.Failed,
        });
    }
    scenarioCompletedWithError(scenarioName, completeWithErrorData) {
        this._trackEvent(TelemetryEventNames.EndScenario, {
            operationName: scenarioName,
            ...completeWithErrorData,
            scenarioName,
            scenarioResult: ScenarioResults.SuccessWithErrors,
        });
    }
    flush() {
        this._provider.flush();
    }
    setCustomDimension(_key, _value) {
        this._provider.setDefaultProperty(_key, _value);
    }
    static _EVENT_PREFIX = 'CodeAppsCLI.';
    _trackEvent(eventName, eventData) {
        const operationName = eventData.operationName || '';
        const scrubbed = getScrubbedCustomDimensions(eventName, operationName, eventData);
        const properties = {};
        for (const [key, value] of Object.entries(scrubbed)) {
            if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
                properties[key] = value;
            }
            else {
                properties[key] = String(value);
            }
        }
        if (operationName) {
            properties.operationName = `${OneDSWriter._EVENT_PREFIX}${operationName}`;
        }
        this._provider.track({
            eventName,
            timestamp: new Date().toISOString(),
            severity: 'info',
            sequenceNumber: this._sequenceNumber++,
            properties,
        });
    }
}
//# sourceMappingURL=OneDSWriter.js.map