"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getFeatureFlagService = getFeatureFlagService;
const posthog_node_1 = require("posthog-node");
const logger_1 = require("../utils/logger");
const ConfigManager_1 = require("./ConfigManager");
const proxy_1 = require("../config/proxy");
const log = (0, logger_1.createLogger)('FeatureFlagService');
const POSTHOG_PUBLIC_API_KEY = 'phc_Ntj9tXHbS64XgYxlTfhglRmFivFsfm0AERph4ZlnNH';
/**
 * Opt out of live PostHog flag evaluation. When set, flags resolve from local
 * registry defaults + env overrides only — deterministic, with no dependency on
 * remote flag state. Used by e2e/CI (see e2e/scripts/start-rivet-e2e.ts).
 */
const remoteFlagsDisabled = () => {
    const v = process.env.RIVET_DISABLE_REMOTE_FLAGS;
    return v !== undefined && v !== 'false' && v !== '0';
};
/**
 * Evaluates PostHog feature flags for the current user.
 *
 * Env-var overrides are handled in evaluateFlags.ts, not here.
 */
class FeatureFlagService {
    posthog = null;
    constructor() {
        if (remoteFlagsDisabled()) {
            log.info('FeatureFlagService: remote flags disabled — using local defaults');
            return;
        }
        try {
            this.posthog = new posthog_node_1.PostHog(POSTHOG_PUBLIC_API_KEY, {
                host: proxy_1.POSTHOG_HOST,
                // Disable periodic flushing — this client is only used for flag reads
                flushAt: 1,
                flushInterval: 0,
            });
            log.info('FeatureFlagService initialized');
        }
        catch (error) {
            log.warn('Failed to initialize FeatureFlagService:', error);
        }
    }
    get defaultUserKey() {
        return (0, ConfigManager_1.getConfigManager)().getEmail() ?? (0, ConfigManager_1.getConfigManager)().getAnonymousId();
    }
    /**
     * Gets the feature flag user key for this evaluation.
     */
    getUserKey(userKey) {
        const trimmedUserKey = userKey?.trim();
        return trimmedUserKey && trimmedUserKey.length > 0
            ? trimmedUserKey
            : this.defaultUserKey;
    }
    /**
     * Fetch all flags for the selected user in a single request.
     */
    async getAllFlags(userKey) {
        if (!this.posthog)
            return {};
        try {
            return await this.posthog.getAllFlags(this.getUserKey(userKey));
        }
        catch (error) {
            log.warn('Failed to fetch feature flags:', error);
            return {};
        }
    }
    /**
     * Evaluate a single flag for the selected user.
     * Useful when a flag key is missing from getAllFlags() (e.g. inactive flags).
     */
    async isFeatureEnabled(key, userKey) {
        if (!this.posthog)
            return null;
        try {
            const enabled = await this.posthog.isFeatureEnabled(key, this.getUserKey(userKey));
            // PostHog can return undefined for flags that are inactive/unresolved.
            // Treat unresolved as disabled; reserve null for transport/runtime failures.
            return enabled ?? false;
        }
        catch (error) {
            log.warn(`Failed to evaluate feature flag "${key}":`, error);
            return null;
        }
    }
    async shutdown() {
        if (this.posthog) {
            await this.posthog.shutdown();
            this.posthog = null;
        }
    }
}
let instance = null;
function getFeatureFlagService() {
    if (!instance) {
        instance = new FeatureFlagService();
    }
    return instance;
}
//# sourceMappingURL=FeatureFlagService.js.map