"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StatsigService = exports.cacheStatsigResult = exports.StatsigReader = void 0;
const tslib_1 = require("tslib");
const node_fetch_1 = tslib_1.__importDefault(require("node-fetch"));
const index_1 = require("../index");
class StatsigReader {
    async testForgeCliTestGate() {
        return (await this.checkGate('forge-cli-test-gate')) ?? false;
    }
    async getForgeCliTestDynamicConfig() {
        return (await this.getDynamicConfig('forge-cli-test-dynamic-configs')) ?? [];
    }
    async isLogsV2ApiEnabled() {
        return (await this.checkGate('is-logs-v-2-api-enabled')) ?? true;
    }
    async isTeamworkGraphProductSupported() {
        return (await this.checkGate('forge-cli-enable-teamwork-graph-product-support')) ?? false;
    }
    async testForgeCliBundleRuntimeLoaderGate() {
        return (await this.checkGate('forge-cli-bundle-runtime-loader')) ?? false;
    }
    async enableCrossProductAppInstallation() {
        return (await this.checkGate('forge-cli-enable-xpa-installation')) ?? false;
    }
    async getDeprecatedRuntimes() {
        return (await this.getDynamicConfig('xls-forge-cli-deprecated-runtimes')) ?? [];
    }
    async isDevSpaceSelectionEnabled() {
        if ((0, index_1.isFedrampEnv)() || process.env.FORGE_CLI_DISABLE_DEV_SPACE === 'true') {
            return false;
        }
        else if (process.env.FORGE_CLI_DISABLE_DEV_SPACE === 'false') {
            return true;
        }
        return (await this.checkGate('forge-cli-enable-developer-space-flow')) ?? false;
    }
    async isTypescriptBundlerEnabled() {
        return (await this.checkGate('forge-cli-enable-typescript-bundler')) ?? false;
    }
    async isSelfManagedTunnelEnabled() {
        return (await this.checkGate('forge-cli-enable-self-managed-tunnel')) ?? false;
    }
}
exports.StatsigReader = StatsigReader;
var STATSIG_API_KEYS;
(function (STATSIG_API_KEYS) {
    STATSIG_API_KEYS["DEV"] = "8821cc19-368d-43d4-a20d-c6b8dca6b7ee";
    STATSIG_API_KEYS["STG"] = "a821948e-f0a9-4fae-b211-7ea7a666ccc5";
    STATSIG_API_KEYS["PROD"] = "b63235cf-e03e-460b-aa2c-f071b3986a0c";
    STATSIG_API_KEYS["FEDRAMP_MODERATE_STAGING"] = "a821948e-f0a9-4fae-b211-7ea7a666ccc5";
    STATSIG_API_KEYS["FEDRAMP_MODERATE_PROD"] = "b63235cf-e03e-460b-aa2c-f071b3986a0c";
})(STATSIG_API_KEYS || (STATSIG_API_KEYS = {}));
var BASE_FEATURE_FLAG_SERVICE_URL;
(function (BASE_FEATURE_FLAG_SERVICE_URL) {
    BASE_FEATURE_FLAG_SERVICE_URL["DEV"] = "https://api.stg.atlassian.com/flags/api/v2/";
    BASE_FEATURE_FLAG_SERVICE_URL["STG"] = "https://api.stg.atlassian.com/flags/api/v2/";
    BASE_FEATURE_FLAG_SERVICE_URL["PROD"] = "https://api.atlassian.com/flags/api/v2/";
    BASE_FEATURE_FLAG_SERVICE_URL["FEDRAMP_MODERATE_STAGING"] = "https://api.stg.atlassian.com/flags/api/v2/";
    BASE_FEATURE_FLAG_SERVICE_URL["FEDRAMP_MODERATE_PROD"] = "https://api.atlassian.com/flags/api/v2/";
})(BASE_FEATURE_FLAG_SERVICE_URL || (BASE_FEATURE_FLAG_SERVICE_URL = {}));
function cacheStatsigResult(getter) {
    const cacheDict = new Map();
    return async function (...args) {
        const relevantArgs = args.filter((arg) => arg !== undefined);
        const cacheKey = JSON.stringify(relevantArgs);
        if (cacheDict.has(cacheKey)) {
            return cacheDict.get(cacheKey);
        }
        const value = await getter.apply(this, args);
        cacheDict.set(cacheKey, value);
        return value;
    };
}
exports.cacheStatsigResult = cacheStatsigResult;
class StatsigService extends StatsigReader {
    logger;
    cliDetails;
    credentialStore;
    appConfigReader;
    getEnvironmentFn;
    constructor(logger, cliDetails, credentialStore, appConfigReader, getEnvironmentFn = index_1.getEnvironmentConfig) {
        super();
        this.logger = logger;
        this.cliDetails = cliDetails;
        this.credentialStore = credentialStore;
        this.appConfigReader = appConfigReader;
        this.getEnvironmentFn = getEnvironmentFn;
    }
    appID = cacheStatsigResult(async () => {
        try {
            const config = await this.appConfigReader.readConfigSection();
            return config === 'missing' || config === 'invalid' ? null : config.id;
        }
        catch {
            return null;
        }
    });
    context = cacheStatsigResult(async () => {
        const context = {};
        try {
            const { accountId } = await this.credentialStore.getCredentials();
            if (accountId) {
                context.accountId = accountId;
            }
        }
        catch { }
        const appID = await this.appID();
        if (appID) {
            context.appId = appID.split('/')[1];
        }
        if (this.cliDetails) {
            context.version = this.cliDetails.version;
        }
        return context;
    });
    fetchGates = async (customAttributes) => {
        try {
            const baseURL = this.getEnvironmentFn(BASE_FEATURE_FLAG_SERVICE_URL);
            const apiKey = this.getEnvironmentFn(STATSIG_API_KEYS);
            const context = await this.context();
            const response = await (0, node_fetch_1.default)(`${baseURL}/frontend/gates`, {
                headers: {
                    'x-api-key': apiKey,
                    'Content-Type': 'application/json'
                },
                method: 'POST',
                body: JSON.stringify({
                    identifiers: {
                        atlassianAccountId: context.accountId,
                        randomizationId: context.appId
                    },
                    customAttributes: {
                        appId: context.appId,
                        version: context.version,
                        atlassianAccountId: context.accountId,
                        ...customAttributes
                    },
                    targetApp: 'forge_cli'
                })
            });
            return await response.json();
        }
        catch (error) {
            this.logger.debug(`Failed to fetch gates: ${error}`);
            return {};
        }
    };
    fetchDynamicConfigs = async (metadata) => {
        try {
            const baseURL = this.getEnvironmentFn(BASE_FEATURE_FLAG_SERVICE_URL);
            const apiKey = this.getEnvironmentFn(STATSIG_API_KEYS);
            const context = await this.context();
            const response = await (0, node_fetch_1.default)(`${baseURL}/configurations`, {
                headers: {
                    'x-api-key': apiKey,
                    'Content-Type': 'application/json'
                },
                method: 'POST',
                body: JSON.stringify({
                    identifiers: {
                        atlassianAccountId: context.accountId,
                        randomizationId: context.appId
                    },
                    metadata: {
                        appId: context.appId,
                        version: context.version,
                        atlassianAccountId: context.accountId,
                        ...metadata
                    },
                    namespace: 'forge_cli'
                })
            });
            return await response.json();
        }
        catch (error) {
            this.logger.debug(`Failed to fetch dynamic configurations: ${error}`);
            return { 'forge-cli-test-dynamic-configs': { value: [] } };
        }
    };
    gatesClient = cacheStatsigResult(async (customAttributes) => {
        const gates = await this.fetchGates(customAttributes);
        return { gates };
    });
    dynamicConfigClient = cacheStatsigResult(async (metadata) => {
        const dynamicConfigs = await this.fetchDynamicConfigs(metadata);
        return { dynamicConfigs };
    });
    async checkGate(gate, customAttributes = {}) {
        try {
            const { gates } = await this.gatesClient(customAttributes, {});
            return gates[gate] ?? null;
        }
        catch (error) {
            if (this.logger.traceEnabled) {
                this.logger.warn(index_1.Text.warning.statsigFetchFailed('feature gates'));
            }
            return null;
        }
    }
    async getDynamicConfig(dynamicConfig, metadata = {}) {
        try {
            const { dynamicConfigs } = await this.dynamicConfigClient({}, metadata);
            return dynamicConfigs[dynamicConfig].value ?? null;
        }
        catch (error) {
            if (this.logger.traceEnabled) {
                this.logger.warn(index_1.Text.warning.statsigFetchFailed('dynamic configurations'));
            }
            return null;
        }
    }
}
exports.StatsigService = StatsigService;
