import { getPlatformAccessToken } from '../lib/authSession';
import { tradingRuntime } from '../lib/runtime';
import { createRequestId } from '../../../shared/request-id.js';
import type { TradingFeatureFlagsResponse } from '../../../shared/feature-flags.js';

export interface BacktestRuntimeFlags {
  enableBacktest: boolean;
  customerEnabled: boolean;
}

const CACHE_TTL_MS = 15_000;
let runtimeFlagsCache: BacktestRuntimeFlags | null = null;
let runtimeFlagsCachedAt = 0;

const toBoolean = (value: unknown, fallback: boolean = false): boolean => {
    if (typeof value === 'boolean') return value;
    if (typeof value === 'string') {
        const normalized = value.trim().toLowerCase();
        if (['true', '1', 'yes', 'on'].includes(normalized)) return true;
        if (['false', '0', 'no', 'off'].includes(normalized)) return false;
    }
    if (typeof value === 'number') {
        if (value === 1) return true;
        if (value === 0) return false;
    }
    return fallback;
};

export const isBacktestBuildEnabled = (): boolean => {
    const raw = import.meta.env.VITE_BACKTEST_ENABLED;
    if (raw === undefined || String(raw).trim() === '') {
        // Default to disabled — backtest is not yet production-ready.
        return false;
    }
    return toBoolean(raw, false);
};

export const clearBacktestRuntimeFlagCache = (): void => {
    runtimeFlagsCache = null;
    runtimeFlagsCachedAt = 0;
};

export const loadBacktestRuntimeFlags = async (): Promise<BacktestRuntimeFlags> => {
    const now = Date.now();
    if (runtimeFlagsCache && (now - runtimeFlagsCachedAt) < CACHE_TTL_MS) {
        return runtimeFlagsCache;
    }

    const accessToken = await getPlatformAccessToken().catch(() => null);
    if (!accessToken) {
        const fallback = { enableBacktest: false, customerEnabled: false };
        runtimeFlagsCache = fallback;
        runtimeFlagsCachedAt = now;
        return fallback;
    }

    const apiUrl = tradingRuntime.tradingApiUrl;
    const response = await fetch(`${apiUrl}/api/feature-flags`, {
        headers: {
            Authorization: `Bearer ${accessToken}`,
            'x-request-id': createRequestId('web-flags')
        }
    });
    if (!response.ok) {
        throw new Error(`Failed to fetch feature flags (${response.status})`);
    }

    const body = await response.json().catch(() => ({} as TradingFeatureFlagsResponse));
    const loaded: BacktestRuntimeFlags = {
        enableBacktest: toBoolean(body?.backtest?.enableBacktest, false),
        customerEnabled: toBoolean(body?.backtest?.customerEnabled, false)
    };

    runtimeFlagsCache = loaded;
    runtimeFlagsCachedAt = Date.now();
    return loaded;
};
