import { config } from '../../config/index.js';
import { IRule, MarketContext, RuleResult, SignalDirection } from './types.js';
import { Indicators } from '../../utils/indicators.js';

export class MomentumRule implements IRule {
    public name = 'MomentumRule';

    public isEnabled(): boolean {
        return config.PRO_STRATEGY.ENABLED_RULES.includes('momentum');
    }

    public async check(context: MarketContext, params?: Record<string, any>): Promise<RuleResult> {
        const timeframe = (params?.timeframe as string) || config.PRO_STRATEGY.PARAMETERS.MOMENTUM_TIMEFRAME;
        const rsiPeriod = Number(params?.rsiPeriod ?? config.PRO_STRATEGY.PARAMETERS.RSI_PERIOD);
        const overbought = Number(params?.overbought ?? config.PRO_STRATEGY.PARAMETERS.RSI_OVERBOUGHT);
        const oversold = Number(params?.oversold ?? config.PRO_STRATEGY.PARAMETERS.RSI_OVERSOLD);
        const candles = timeframe === '15m' ? context.candles15m : context.candles1h;
        const closes = candles.map(c => c.close);
        const rsi = Indicators.calculateRSI(closes, rsiPeriod);

        if (rsi === undefined) {
            return {
                ruleName: this.name,
                passed: false,
                reason: `Insufficient ${timeframe} data for RSI(${rsiPeriod})`
            };
        }

        const isMajor = context.isMajorSession;
        const buyThreshold = isMajor ? 50 : 60;
        const sellThreshold = isMajor ? 50 : 40;

        let signal = SignalDirection.NONE;
        let passed = false;
        let reason = '';

        if (rsi > buyThreshold && rsi < overbought) {
            signal = SignalDirection.BUY;
            passed = true;
            reason = isMajor
                ? `Bullish Momentum (RSI ${rsi.toFixed(1)} > 50)`
                : `Strong Bullish Momentum Required (RSI ${rsi.toFixed(1)} > 60)`;
        } else if (rsi < sellThreshold && rsi > oversold) {
            signal = SignalDirection.SELL;
            passed = true;
            reason = isMajor
                ? `Bearish Momentum (RSI ${rsi.toFixed(1)} < 50)`
                : `Strong Bearish Momentum Required (RSI ${rsi.toFixed(1)} < 40)`;
        } else {
            reason = isMajor
                ? `Momentum weak or extreme (RSI ${rsi.toFixed(1)})`
                : `Momentum insufficient for Minor Session (RSI ${rsi.toFixed(1)} needs >60 or <40)`;
        }

        return {
            ruleName: this.name,
            passed,
            signal,
            reason
        };
    }
}
