"""MIC02 — Engulfing continuation (trend-filtered).

HYPOTHESIS:
  Bullish engulfing in an uptrend  -> long at close of engulfing bar.
  Bearish engulfing in a downtrend -> short at close of engulfing bar.
  Trend filter: EMA(trend_win) direction.

Pattern definition (standard engulfing, CAUSAL):
  Bullish engulfing at bar i:
    - Bar i-1 is bearish: close[i-1] < open[i-1]
    - Bar i is bullish:   close[i] > open[i]
    - Bar i's body ENGULFS bar i-1's body: open[i] <= close[i-1] AND close[i] >= open[i-1]
  Bearish engulfing at bar i:
    - Bar i-1 is bullish: close[i-1] > open[i-1]
    - Bar i is bearish:   close[i] < open[i]
    - Bar i's body ENGULFS bar i-1's body: open[i] >= close[i-1] AND close[i] <= open[i-1]

Trend filter: EMA(trend_win). Long only if close[i] > EMA[i]. Short only if close[i] < EMA[i].

Entry fills at close[i]. Exit after max_bars (time-stop only).

Grid: (trend_win, max_bars) x 2 assets x 1 TF = 4 backtests (<=6 limit respected).

Causality: all decisions use data <= close[i] (open[i] is known at close[i]).
No entry on candle extreme (high/low). Entry at close[i].
"""
import sys
sys.path.insert(0, "/opt/docker/PythagorasGoal/scripts/research/alt")
import altlib as al
import numpy as np


def make_entries(trend_win: int, max_bars: int):
    """Return entries_fn for given EMA trend window and max hold bars."""
    def entries_fn(df):
        o = df["open"].values
        c = df["close"].values
        n = len(c)

        # Causal EMA of close
        trend = al.ema(c, span=trend_win)

        entries = [None] * n

        for i in range(1, n):
            # --- Bullish engulfing ---
            # Previous bar bearish
            prev_bear = c[i-1] < o[i-1]
            # Current bar bullish
            curr_bull = c[i] > o[i]
            # Engulf: current open <= prev close AND current close >= prev open
            bull_engulf = (o[i] <= c[i-1]) and (c[i] >= o[i-1])
            # Trend filter: close above EMA
            uptrend = np.isfinite(trend[i]) and (c[i] > trend[i])

            if prev_bear and curr_bull and bull_engulf and uptrend:
                entries[i] = {
                    "dir": +1,
                    "tp": None,
                    "sl": None,
                    "max_bars": max_bars,
                }
                continue

            # --- Bearish engulfing ---
            # Previous bar bullish
            prev_bull = c[i-1] > o[i-1]
            # Current bar bearish
            curr_bear = c[i] < o[i]
            # Engulf: current open >= prev close AND current close <= prev open
            bear_engulf = (o[i] >= c[i-1]) and (c[i] <= o[i-1])
            # Trend filter: close below EMA
            downtrend = np.isfinite(trend[i]) and (c[i] < trend[i])

            if prev_bull and curr_bear and bear_engulf and downtrend:
                entries[i] = {
                    "dir": -1,
                    "tp": None,
                    "sl": None,
                    "max_bars": max_bars,
                }

        return entries
    return entries_fn


# Internal grid: 2 param sets x 2 assets x 1 TF = 4 backtests (within <=6)
GRID = [
    (50, 5),    # medium-term trend, short hold
    (100, 10),  # longer-term trend, medium hold
]

best_rep = None
best_score = -999.0
best_params = None

for trend_win, max_bars in GRID:
    rep = al.study_signals(
        f"MIC02-ema{trend_win}-mb{max_bars}",
        make_entries(trend_win=trend_win, max_bars=max_bars),
        tfs=("1d",),
    )
    v = rep["verdict"]
    score = v.get("best_holdout_sharpe", -999.0)
    print(f"ema={trend_win:3d} max_bars={max_bars:2d}: grade={v['grade']} "
          f"minFull={v.get('best_full_sharpe'):+.3f} minHold={v.get('best_holdout_sharpe'):+.3f}")
    if score > best_score:
        best_score = score
        best_rep = rep
        best_params = (trend_win, max_bars)

print(f"\nBest config: ema={best_params[0]}, max_bars={best_params[1]}")
print(al.fmt(best_rep))
print("JSON:", al.as_json(best_rep))
