package top.baogutang.strategy.strategies;

import top.baogutang.strategy.commons.enums.Timeframe;
import top.baogutang.strategy.models.Kline;
import top.baogutang.strategy.models.Signal;
import top.baogutang.strategy.models.StrategyContext;
import top.baogutang.strategy.services.IndicatorService;

import java.util.*;

public class StrategyMeanRevertShort implements Strategy {
    private final double r1Low, r1High;

    public StrategyMeanRevertShort(double r1Low, double r1High) {
        this.r1Low = r1Low;
        this.r1High = r1High;
    }

    public String name() {
        return "MeanRevertShort";
    }

    public Optional<Signal> evaluate(StrategyContext ctx) {
        java.util.List<Kline> h1 = ctx.getCache().lastN(Timeframe.H1, 120);
        if (h1.size() < 50) return Optional.empty();
        Kline last = h1.get(h1.size() - 1);
        if (!last.finalBar()) return Optional.empty();
        IndicatorService ind = ctx.getIndicators();
        double ma7 = ind.sma(h1, 7);
        double ma30 = ind.sma(h1, 30);
        if (!(ma7 < ma30)) return Optional.empty();
        boolean inR1 = last.high() >= r1Low && last.close() <= r1High;
        if (!inR1) return Optional.empty();
        Kline h1_1 = h1.get(h1.size() - 2);
        Kline h1_2 = h1.get(h1.size() - 3);
        double prevMax = Math.max(h1_1.high(), h1_2.high());
        if (last.high() > prevMax * 1.002) return Optional.empty();
        double avgVol20 = ind.smaVolume(h1, 20);
        double recent3 = 0;
        for (int i = h1.size() - 3; i < h1.size(); i++) recent3 += h1.get(i).volume();
        recent3 /= 3.0;
        if (recent3 > avgVol20 * 1.05) return Optional.empty();
        double entry = Math.min(last.close(), r1High - (r1High - r1Low) * 0.3);
        double stop = r1High + (r1High - r1Low) * 0.4;
        double[] targets = new double[]{
                r1Low - (r1High - r1Low) * 1.0,
                r1Low - (r1High - r1Low) * 1.8,
                r1Low - (r1High - r1Low) * 3.0
        };
        String comment = String.format("ma7=%.2f ma30=%.2f volFactor=%.2f", ma7, ma30, recent3 / avgVol20);
        Signal sig = new Signal(java.util.UUID.randomUUID().toString(),
                ctx.getNow(), ctx.getSymbol(), name(), "SHORT",
                entry, stop, targets, "A", comment);
        return Optional.of(sig);
    }
}
