import { config } from '../config/index.js';
import logger from './logger.js';

export class SymbolMapper {
    private static normalizeSymbolToken(symbol: string): string {
        return String(symbol || '')
            .trim()
            .toUpperCase()
            .replace(/_/g, '/')
            .replace(/-/g, '/')
            .replace(/\s+/g, '');
    }

    /**
     * Converts a data symbol (e.g. BTC/USDT) to a tradeable symbol for the execution exchange (e.g. BTC/USD for Alpaca).
     */
    static toTradeSymbol(symbol: string, provider: string): string {
        if (provider.toLowerCase() === 'alpaca') {
            // Alpaca prefers USD over USDT for many crypto pairs
            const mapped = symbol.replace('/USDT', '/USD');
            if (mapped !== symbol) {
                logger.info(`[SymbolMapper] Mapped ${symbol} to ${mapped} for Alpaca execution.`);
            }
            return mapped;
        }
        return symbol;
    }

    /**
     * Returns a normalized symbol key aligned to execution provider semantics.
     * Example (alpaca): BTC/USDT and BTC/USD normalize to BTC/USD.
     */
    static toExecutionScopeSymbol(symbol: string, provider: string): string {
        const normalizedInput = this.normalizeSymbolToken(symbol);
        const tradeSymbol = this.toTradeSymbol(normalizedInput, provider);
        return this.normalizeSymbolToken(tradeSymbol);
    }

    /**
     * Optional: Map back if needed for tracking
     */
    static toDataSymbol(symbol: string, provider: string): string {
        if (provider.toLowerCase() === 'alpaca') {
            return symbol.replace('/USD', '/USDT');
        }
        return symbol;
    }
}
