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

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

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

    public async check(context: MarketContext, params?: Record<string, any>): Promise<RuleResult> {
        const timeframe = (params?.timeframe as string) || config.PRO_STRATEGY.PARAMETERS.EXECUTION_TIMEFRAME;
        const ema20 = (timeframe === '15m') ? context.ema20_15m : context.ema20_1h;

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

        const price = context.currentPrice;

        // Calculate "Extension" from EMA
        // If price is > 1-2% away from EMA, it's extended.
        const diffPercent = Math.abs(price - ema20) / ema20 * 100;
        const rawMaxExtension = Number(params?.zonePercent ?? 1.5);
        const MAX_EXTENSION = Number.isFinite(rawMaxExtension) && rawMaxExtension > 0 ? rawMaxExtension : 1.5;

        // This rule validates "Location".
        // Ideally we want to buy on a pullback, close to the EMA.
        // If we are too far, we skip.

        let passed = true;
        let reason = `Price is within ${diffPercent.toFixed(2)}% of EMA20 (Value Zone)`;

        if (diffPercent > MAX_EXTENSION) {
            passed = false;
            reason = `Price overextended (${diffPercent.toFixed(2)}% > ${MAX_EXTENSION}%) from EMA20. Wait for pullback.`;
        }

        return {
            ruleName: this.name,
            passed,
            signal: SignalDirection.NONE, // This rule filters, doesn't signal direction itself
            reason
        };
    }
}
