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

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

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

    public async check(context: MarketContext, params?: Record<string, any>): Promise<RuleResult> {
        const fastPeriod = Number(params?.fastPeriod ?? 50);
        const slowPeriod = Number(params?.slowPeriod ?? 200);
        if (!Number.isFinite(fastPeriod) || !Number.isFinite(slowPeriod) || fastPeriod <= 0 || slowPeriod <= 0 || fastPeriod >= slowPeriod) {
            return {
                ruleName: this.name,
                passed: false,
                reason: `Invalid TrendBias params (fast=${fastPeriod}, slow=${slowPeriod})`
            };
        }

        const close4h = context.candles4h.map(c => c.close);
        if (close4h.length < slowPeriod + 1) {
            return {
                ruleName: this.name,
                passed: false,
                reason: `Insufficient 4H data for EMA${fastPeriod}/EMA${slowPeriod}`
            };
        }

        const price = context.currentPrice;
        const emaFast = Indicators.calculateEMA(close4h, fastPeriod);
        const emaSlow = Indicators.calculateEMA(close4h, slowPeriod);

        // Uptrend: Price > 50 > 200
        if (price > emaFast && emaFast > emaSlow) {
            return {
                ruleName: this.name,
                passed: true,
                signal: SignalDirection.BUY,
                reason: `4H Uptrend (Price > EMA${fastPeriod} > EMA${slowPeriod})`
            };
        }

        // Downtrend: Price < 50 < 200
        if (price < emaFast && emaFast < emaSlow) {
            return {
                ruleName: this.name,
                passed: true,
                signal: SignalDirection.SELL,
                reason: `4H Downtrend (Price < EMA${fastPeriod} < EMA${slowPeriod})`
            };
        }

        // Ranging / No Clear Trend
        return {
            ruleName: this.name,
            passed: false,
            signal: SignalDirection.NONE,
            reason: `No clear 4H trend bias for EMA${fastPeriod}/EMA${slowPeriod}`
        };
    }
}
