"""BRK09 — Inside-bar breakout (1d, discrete signals).

HYPOTHESIS:
  An "inside bar" is a bar whose high < previous bar's high AND low > previous bar's low
  (fully within the "mother bar"). This signals consolidation. When the NEXT bar's close
  breaks above the mother-bar's high -> long entry at that close. If it breaks below the
  mother-bar's low -> short entry. TP/SL based on ATR multiples.

CAUSAL GUARANTEE: All signals decided with data <= close[i], filled at close[i].

GRID (<=4 configs, total <=6 backtests = 4 configs * 1 TF, plus 2 extra for fee sweep
  handled internally by study_signals):
  We vary:
    - sl_atr: stop-loss in ATR multiples (1.5 or 2.0)
    - max_bars: max holding period in bars (5 or 10)
  That gives 4 combinations on 1d. Total cells = 4 * 2 assets = 8 backtests per config,
  but study_signals runs BTC+ETH per config automatically. We pick best.

ENTRY: close of the breakout bar (the bar that breaks mother-bar high/low).
EXIT: TP = entry +/- sl_atr * atr (2:1 R:R), SL = entry -/+ sl_atr * atr, max_bars.
"""
import sys
sys.path.insert(0, "/opt/docker/PythagorasGoal/scripts/research/alt")
import altlib as al
import numpy as np


def make_entries(df, sl_atr: float = 1.5, max_bars: int = 5):
    """Generate inside-bar breakout entries on 1d bars.

    Logic (all at bar i, using data <= close[i]):
      - bar i-1 is the "inside bar": inside_bar[i-1] = True if:
          high[i-1] < high[i-2] AND low[i-1] > low[i-2]
      - bar i is the "breakout bar": breaks above mother-bar (i-2) high or below low
          long  if close[i] > high[i-2] AND inside_bar[i-1]
          short if close[i] < low[i-2]  AND inside_bar[i-1]

    We need at least i>=2 to have i-1 and i-2. We also check that the inside bar
    hasn't already seen a breakout mid-bar (i.e., we only care about close-to-close).
    """
    h = df["high"].values
    l = df["low"].values
    c = df["close"].values
    atr_vals = al.atr(df, win=14)

    entries = [None] * len(df)

    for i in range(2, len(df)):
        # Check if bar i-1 is an inside bar (contained within bar i-2)
        is_inside = (h[i-1] < h[i-2]) and (l[i-1] > l[i-2])
        if not is_inside:
            continue

        mother_high = h[i-2]
        mother_low = l[i-2]
        entry_price = c[i]
        atr_i = atr_vals[i]

        if atr_i <= 0 or not np.isfinite(atr_i):
            continue

        sl_dist = sl_atr * atr_i
        tp_dist = 2.0 * sl_dist  # 2:1 R:R

        # Long breakout: close breaks above mother-bar high
        if c[i] > mother_high:
            tp = entry_price + tp_dist
            sl = entry_price - sl_dist
            entries[i] = {"dir": +1, "tp": tp, "sl": sl, "max_bars": max_bars}
        # Short breakout: close breaks below mother-bar low
        elif c[i] < mother_low:
            tp = entry_price - tp_dist
            sl = entry_price + sl_dist
            entries[i] = {"dir": -1, "tp": tp, "sl": sl, "max_bars": max_bars}

    return entries


# Grid: 4 configs
CONFIGS = [
    {"sl_atr": 1.5, "max_bars": 5},
    {"sl_atr": 1.5, "max_bars": 10},
    {"sl_atr": 2.0, "max_bars": 5},
    {"sl_atr": 2.0, "max_bars": 10},
]

best_rep = None
best_score = -999.0

for cfg in CONFIGS:
    name = f"BRK09_sl{cfg['sl_atr']}_mb{cfg['max_bars']}"
    rep = al.study_signals(
        name,
        lambda df, c=cfg: make_entries(df, sl_atr=c["sl_atr"], max_bars=c["max_bars"]),
        tfs=("1d",),
    )
    v = rep["verdict"]
    score = v.get("best_holdout_sharpe", -999.0) or -999.0
    print(f"  {name}: grade={v['grade']} full={v.get('best_full_sharpe')} hold={v.get('best_holdout_sharpe')}")
    if score > best_score:
        best_score = score
        best_rep = rep
        best_rep["name"] = "BRK09"  # rename to canonical

print()
print(al.fmt(best_rep))
print("JSON:", al.as_json(best_rep))
