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

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

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

    public async check(context: MarketContext, params?: Record<string, any>): Promise<RuleResult> {
        const requestedTimeframe = String(params?.timeframe || '').toLowerCase();
        const defaultTimeframe = config.PRO_STRATEGY.PARAMETERS.EXECUTION_TIMEFRAME;
        const timeframe = requestedTimeframe === '15m' || requestedTimeframe === '1h'
            ? requestedTimeframe
            : defaultTimeframe;
        const wickThresholdRaw = Number(params?.wickRatioThreshold ?? params?.wickThreshold ?? 0.5);
        const wickThreshold = Number.isFinite(wickThresholdRaw)
            ? Math.max(0.1, Math.min(0.95, wickThresholdRaw))
            : 0.5;
        const enableEmaReclaim = params?.enableEmaReclaim !== false;
        const enableWickRejection = params?.enableWickRejection !== false
            && params?.showPatterns !== false;

        const candles = (timeframe === '15m') ? context.candles15m : context.candles1h;
        const ema20 = (timeframe === '15m') ? context.ema20_15m : context.ema20_1h;

        if (candles.length < 3) return { ruleName: this.name, passed: false, reason: 'Insufficient data' };

        const current = candles[candles.length - 1]; // This is the "Closed" candle we are analyzing
        const prev = candles[candles.length - 2];     // The one before it

        if (!ema20) return { ruleName: this.name, passed: false, reason: `No EMA20 data for ${timeframe}` };

        // We need to know the INTENDED direction (Bias).
        // Since we don't have the Bias passed in directly here easily without coupling,
        // we can infer it or checking if the rule engine passes context metadata.
        // For simplicity, let's check for ANY valid trigger.

        // TRIGGER 1: EMA RECLAIM (Bullish)
        // Previous CLose < EMA, Current Close > EMA
        const isBullishReclaim = prev.close < ema20 && current.close > ema20;

        // TRIGGER 2: REJECTION WICK (Bullish)
        // Lower wick is > 50% of total candle size
        const totalSize = current.high - current.low;
        if (totalSize <= 0) {
            return {
                ruleName: this.name,
                passed: false,
                signal: SignalDirection.NONE,
                reason: 'Flat/invalid candle range; wick ratio check skipped'
            };
        }
        const lowerWick = Math.min(current.open, current.close) - current.low;
        const isBullishWick = (lowerWick / totalSize) > wickThreshold;

        // TRIGGER 3: RSI TURN (Bullish)
        // RSI crossed above 30 or 50?
        // Let's stick to Candle Patterns for now as requested.

        if (enableEmaReclaim && isBullishReclaim) {
            return {
                ruleName: this.name,
                passed: true,
                signal: SignalDirection.BUY,
                reason: 'Entry Trigger: EMA20 Reclaim (Price crossed back above EMA)'
            };
        }

        if (enableWickRejection && isBullishWick) {
            return {
                ruleName: this.name,
                passed: true,
                signal: SignalDirection.BUY,
                reason: `Entry Trigger: Bullish Rejection Wick detected (threshold ${wickThreshold.toFixed(2)})`
            };
        }

        // Bearish Logic (Inverse)
        const isBearishReclaim = prev.close > ema20 && current.close < ema20;
        const upperWick = current.high - Math.max(current.open, current.close);
        const isBearishWick = (upperWick / totalSize) > wickThreshold;

        if (enableEmaReclaim && isBearishReclaim) {
            return {
                ruleName: this.name,
                passed: true,
                signal: SignalDirection.SELL,
                reason: 'Entry Trigger: EMA20 Loss (Price crossed back below EMA)'
            };
        }

        if (enableWickRejection && isBearishWick) {
            return {
                ruleName: this.name,
                passed: true,
                signal: SignalDirection.SELL,
                reason: `Entry Trigger: Bearish Rejection Wick detected (threshold ${wickThreshold.toFixed(2)})`
            };
        }

        return {
            ruleName: this.name,
            passed: false,
            signal: SignalDirection.NONE,
            reason: 'No specific entry trigger (Wait for EMA Reclaim or Wick)'
        };
    }
}
