"""CMB05 — BB Squeeze -> Breakout (honest, leak-free).

HYPOTHESIS: Bollinger Bandwidth at a multi-bar low (squeeze) then close > upper BB
-> enter long at that close (entry at close[i], direction decided with data<=close[i]).
Exit when close drops back below middle band, or max_bars reached, or SL hit.

Tested on 1d only (study_signals, discrete). Small grid on:
  - BB window: 20 vs 30
  - Squeeze lookback: 50 vs 100
  Total configs: 4 — two assets each => 8 backtests. Within budget.
"""
import sys
sys.path.insert(0, "/opt/docker/PythagorasGoal/scripts/research/alt")
import altlib as al
import numpy as np
import pandas as pd


def make_entries(bb_win: int = 20, squeeze_lb: int = 50, squeeze_pct: float = 0.20, sl_mult: float = 2.0, max_bars: int = 30):
    """
    Returns entries_fn(df) -> list[dict|None] for study_signals.

    Squeeze = BB bandwidth (upper-lower)/middle in lowest squeeze_pct quantile over squeeze_lb bars.
    Breakout = close[i] > upper[i] AND bandwidth is in compressed regime.
    Entry: long at close[i], honest (direction decided with close[i]).
    Exit: close < middle band (continuous) OR max_bars OR SL at entry - sl_mult*ATR.
    """
    def entries_fn(df):
        c = df["close"].values.astype(float)
        n = len(c)

        # BB bands - causal (uses data up to i)
        upper, mid, lower = al.bbands(c, win=bb_win, k=2.0)

        # Bandwidth
        bw = np.where(mid != 0, (upper - lower) / mid, np.nan)

        # Squeeze: bandwidth in lowest squeeze_pct percentile over squeeze_lb bars (causal)
        # Use rolling quantile to flag "compressed" bandwidth
        bw_series = pd.Series(bw)
        bw_lo = bw_series.rolling(squeeze_lb, min_periods=squeeze_lb).quantile(squeeze_pct).values

        # ATR for SL
        atr_arr = al.atr(df, win=14)

        entries = [None] * n
        in_trade = False

        for i in range(squeeze_lb + bb_win, n):
            if np.isnan(upper[i]) or np.isnan(bw_lo[i]) or np.isnan(atr_arr[i]):
                continue
            if not np.isfinite(bw[i]):
                continue

            # Squeeze: bandwidth <= its rolling low-percentile threshold
            is_squeeze = bw[i] <= bw_lo[i]

            # Breakout: close[i] > upper[i]  (decided at close[i], honest)
            breakout = c[i] > upper[i]

            if (not in_trade) and is_squeeze and breakout:
                sl_px = c[i] - sl_mult * atr_arr[i]
                entries[i] = {
                    "dir": +1,
                    "tp": None,
                    "sl": sl_px,
                    "max_bars": max_bars,
                }
                in_trade = True
            elif in_trade:
                # Exit signal: close falls below middle band -> reset flag
                if c[i] < mid[i]:
                    in_trade = False

        return entries

    return entries_fn


# Grid: 4 configs (2 bb_win x 2 squeeze_pct) with fixed squeeze_lb=100
configs = [
    dict(bb_win=20, squeeze_lb=100, squeeze_pct=0.20),
    dict(bb_win=20, squeeze_lb=100, squeeze_pct=0.30),
    dict(bb_win=30, squeeze_lb=100, squeeze_pct=0.20),
    dict(bb_win=30, squeeze_lb=100, squeeze_pct=0.30),
]

best_rep = None
best_score = -999.0

print("=== CMB05: BB Squeeze -> Breakout ===")
print(f"Grid: {len(configs)} configs x 2 assets x fee_sweep = honest eval\n")

for cfg in configs:
    name = f"CMB05-BB{cfg['bb_win']}-SQ{cfg['squeeze_lb']}-P{int(cfg['squeeze_pct']*100)}"
    fn = make_entries(bb_win=cfg["bb_win"], squeeze_lb=cfg["squeeze_lb"], squeeze_pct=cfg["squeeze_pct"])
    rep = al.study_signals(name, fn, tfs=("1d",))
    v = rep["verdict"]
    score = v.get("best_holdout_sharpe", -9)
    print(f"  {name}: grade={v['grade']} fullSh={v.get('best_full_sharpe'):.3f} holdSh={v.get('best_holdout_sharpe'):.3f}")
    if score > best_score:
        best_score = score
        best_rep = rep
        best_rep["_cfg"] = cfg

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