import { SlotMachineConfig } from 'src/types/SlotMachineConfig';

// Picks a symbol key based on weights from config.symbolsWeights (if provided).
// - Unspecified symbols get default weight 1.
// - Weight 0 excludes a symbol.
// - If all weights are 0 or invalid, falls back to uniform random among symbolsKeys.
function pickWeightedSymbolKey(config: SlotMachineConfig): string {
    const keys = config.symbolsKeys || [];
    if (!keys.length) return '' as unknown as string;

    const weightsCfg = config.symbolsWeights || {};
    let total = 0;
    const weights: number[] = keys.map((k) => {
        const w = weightsCfg[k];
        const weight = typeof w === 'number' ? Math.max(0, w) : 1;
        total += weight;
        return weight;
    });

    // Fallback to uniform if total weight is 0
    if (total <= 0) {
        const i = Math.floor(Math.random() * keys.length);
        return keys[i];
    }

    let r = Math.random() * total;
    for (let i = 0; i < keys.length; i++) {
        const w = weights[i];
        if (r < w) return keys[i];
        r -= w;
    }
    return keys[keys.length - 1];
}

export const createScreenInputMap = (config: SlotMachineConfig) =>
    new Array(config.reels * config.slots).fill({}).map(() => {
        const key = pickWeightedSymbolKey(config);
        // Derive value from symbol config if provided; otherwise leave undefined to avoid forcing a value
        const cfg = config.symbols?.[key] as any;
        const value = (cfg && typeof cfg.value === 'number' && isFinite(cfg.value) && cfg.value > 0)
            ? cfg.value
            : undefined;
        return { key, value };
    });
