"""MIC07 — Pin-bar rejection reversal (hammer at support).

HYPOTHESIS:
  A hammer candle (large lower wick, small body near top) at a recent support (N-bar low)
  signals a long reversal. Enter long at close[i] with SL below the wick low.

PIN-BAR DEFINITION (causal, using only bar[i] OHLC):
  - Lower wick >= wick_ratio * candle range  (e.g. 60% of H-L)
  - Body is in upper part of the candle (close > midpoint)
  - Candle range > ATR * min_range_atr  (no doji / tiny bars)

SUPPORT CONDITION:
  - low[i] <= rolling_min(low, support_win bars, excluding bar i) * (1 + support_pct)
    i.e. bar is "near" a recent N-bar low

TRADE MANAGEMENT:
  - Entry: close[i]
  - SL: low[i] - atr_sl_mult * ATR  (below wick, some buffer)
  - TP: close[i] + rr_ratio * (close[i] - SL)  (risk-reward)
  - max_bars: hold at most max_hold days

Grid (<=4 configs, 1 TF = 1d, 2 assets => 4 backtests total):
  Config A: wick_ratio=0.60, support_win=20, sl_mult=0.2, rr=2.0, max_hold=10
  Config B: wick_ratio=0.65, support_win=10, sl_mult=0.3, rr=1.5, max_hold=8
  Config C: wick_ratio=0.55, support_win=20, sl_mult=0.3, rr=2.0, max_hold=15
  Config D: wick_ratio=0.60, support_win=30, sl_mult=0.2, rr=2.0, max_hold=10

Pick best config by min_asset_holdout_sharpe, print full report.
"""
import sys
sys.path.insert(0, "/opt/docker/PythagorasGoal/scripts/research/alt")
import altlib as al
import numpy as np


def make_entries(df, wick_ratio=0.60, support_win=20, sl_mult=0.2,
                 rr=2.0, max_hold=10, atr_win=14, min_range_atr=0.3):
    """Build entry list for the pin-bar reversal strategy."""
    o = df["open"].values.astype(float)
    h = df["high"].values.astype(float)
    l = df["low"].values.astype(float)
    c = df["close"].values.astype(float)

    atr_arr = al.atr(df, atr_win)

    # Rolling min of lows over support_win bars PRIOR to i (shift by 1 -> causal)
    low_series = df["low"].rolling(support_win, min_periods=support_win).min().shift(1).values

    entries = [None] * len(df)

    for i in range(support_win + atr_win + 1, len(df)):
        rng = h[i] - l[i]
        if rng <= 0:
            continue

        atr_i = atr_arr[i]
        if not np.isfinite(atr_i) or atr_i <= 0:
            continue

        # Filter tiny candles
        if rng < min_range_atr * atr_i:
            continue

        body_top = max(o[i], c[i])
        body_bot = min(o[i], c[i])

        lower_wick = body_bot - l[i]
        # upper_wick = h[i] - body_top  # not used but useful for debug

        # Pin bar: lower wick must dominate
        if lower_wick < wick_ratio * rng:
            continue

        # Body in upper portion (close > midpoint of range)
        if c[i] <= (h[i] + l[i]) / 2.0:
            continue

        # Support condition: low[i] is near recent N-bar rolling min
        supp = low_series[i]
        if not np.isfinite(supp):
            continue
        # Low[i] must be at or below support level (within 0.5% of the recent low)
        if l[i] > supp * 1.005:
            continue

        # Trade setup
        sl_price = l[i] - sl_mult * atr_i
        if sl_price >= c[i]:
            continue  # degenerate
        risk = c[i] - sl_price
        if risk <= 0:
            continue
        tp_price = c[i] + rr * risk

        entries[i] = {
            "dir": 1,
            "tp": round(tp_price, 2),
            "sl": round(sl_price, 2),
            "max_bars": max_hold,
        }

    return entries


CONFIGS = [
    dict(wick_ratio=0.60, support_win=20, sl_mult=0.2, rr=2.0, max_hold=10),
    dict(wick_ratio=0.65, support_win=10, sl_mult=0.3, rr=1.5, max_hold=8),
    dict(wick_ratio=0.55, support_win=20, sl_mult=0.3, rr=2.0, max_hold=15),
    dict(wick_ratio=0.60, support_win=30, sl_mult=0.2, rr=2.0, max_hold=10),
]

best_rep = None
best_score = -999

for cfg_idx, cfg in enumerate(CONFIGS):
    name = f"MIC07-cfg{cfg_idx+1}"
    rep = al.study_signals(
        name,
        lambda df, c=cfg: make_entries(df, **c),
        tfs=("1d",),
    )
    score = rep["verdict"].get("best_holdout_sharpe", -9)
    print(f"Config {cfg_idx+1}: {cfg} -> score={score:.3f}, grade={rep['verdict']['grade']}")
    if score > best_score:
        best_score = score
        best_rep = rep
        best_cfg = cfg

print("\n=== BEST CONFIG ===", best_cfg)
print(al.fmt(best_rep))
print("JSON:", al.as_json(best_rep))
