import { config } from '../config/index.js';
import { SymbolMapper } from './symbolMapper.js';

export const normalizeBotSymbolToken = (symbolRaw: string | null | undefined): string => {
    const compact = String(symbolRaw || '').trim().toUpperCase().replace(/[^A-Z0-9]/g, '');
    if (compact.endsWith('USDT')) {
        return `${compact.slice(0, -4)}USD`;
    }
    return compact;
};

const deriveSymbolVariants = (symbolRaw: string): string[] => {
    const seed = String(symbolRaw || '').trim();
    if (!seed) return [];

    const variants = new Set<string>([seed]);
    const executionProvider = String(config.EXECUTION_PROVIDER || '').trim();
    try {
        variants.add(SymbolMapper.toTradeSymbol(seed, executionProvider));
    } catch {
        // Keep raw variant when mapper does not support a symbol/provider combination.
    }

    try {
        variants.add(SymbolMapper.toDataSymbol(seed, executionProvider));
    } catch {
        // Keep raw variant when mapper does not support a symbol/provider combination.
    }

    return Array.from(variants).filter(Boolean);
};

export const buildManagedBotSymbolTokenSet = (symbols?: string[]): Set<string> => {
    const configuredSymbols = Array.isArray(symbols) && symbols.length > 0
        ? symbols
        : (Array.isArray(config.SYMBOLS) ? config.SYMBOLS : []);

    const tokens = new Set<string>();
    for (const configured of configuredSymbols) {
        for (const variant of deriveSymbolVariants(String(configured || ''))) {
            const token = normalizeBotSymbolToken(variant);
            if (token) tokens.add(token);
        }
    }

    return tokens;
};

export const isManagedBotSymbol = (
    symbolRaw: string | null | undefined,
    managedTokens?: Set<string>
): boolean => {
    const token = normalizeBotSymbolToken(symbolRaw);
    if (!token) return false;
    const scope = managedTokens || buildManagedBotSymbolTokenSet();
    return scope.has(token);
};
