import { supabase } from '../lib/supabaseClient';
import { tradingRuntime } from '../lib/runtime';

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 enabled unless explicitly disabled at build-time.
        return true;
    }
    return toBoolean(raw, true);
};

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 sessionData = await supabase.auth.getSession();
    const accessToken = sessionData?.data?.session?.access_token;
    if (!accessToken) {
        const fallback = { enableBacktest: false, customerEnabled: false };
        runtimeFlagsCache = fallback;
        runtimeFlagsCachedAt = now;
        return fallback;
    }

    const apiUrl = tradingRuntime.tradingApiUrl;
    const response = await fetch(`${apiUrl}/api/config`, {
        headers: {
            Authorization: `Bearer ${accessToken}`
        }
    });
    if (!response.ok) {
        throw new Error(`Failed to fetch runtime config (${response.status})`);
    }

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

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