"""BRK04 — Bollinger Breakout (vol expansion), momentum interpretation.

HYPOTHESIS: Long-flat when close > upper BB(win, k); exit to flat when close < mid BB.
This is a momentum (trend-following) reading of Bollinger Band breakouts — price above
the upper band means the move is strong enough to be outside 2-sigma, so we ride it.

Internal grid (<=4 configs, total backtests <=6):
  Config A: BB(20, 2.0), tfs=("1d",)   -- canonical params
  Config B: BB(20, 1.5), tfs=("1d",)   -- tighter band (more signals)
  Config C: BB(30, 2.0), tfs=("1d",)   -- wider lookback
  Config D: BB(20, 2.0) + vol_target,  tfs=("1d",)  -- vol-sized

We use bbands() which is causal at bar i (uses data up to i).
Entry/exit logic is also causal — no look-ahead.
The lib shift means target[i] is held during bar i+1.
"""
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 _bb_long_flat(df: pd.DataFrame, win: int = 20, k: float = 2.0,
                  use_vol_target: bool = False) -> np.ndarray:
    """Causal BB breakout: long when close > upper band, flat when close < mid band.
    State machine with forward-fill between entry and exit signals."""
    c = df["close"].values.astype(float)
    upper, mid, lower = al.bbands(c, win=win, k=k)

    # State: 1 = in long, 0 = flat
    # At bar i:
    #   - if state was 0 (flat): enter long if close[i] > upper[i]
    #   - if state was 1 (long): exit to flat if close[i] < mid[i]
    # Result is decided at close[i], held during bar i+1 (shift done by lib).
    n = len(c)
    target = np.zeros(n)
    state = 0  # start flat

    for i in range(n):
        if np.isnan(upper[i]) or np.isnan(mid[i]):
            target[i] = 0.0
            continue
        if state == 0:
            # Check entry: close above upper band
            if c[i] > upper[i]:
                state = 1
        else:  # state == 1, in long
            # Check exit: close below mid band
            if c[i] < mid[i]:
                state = 0
        target[i] = float(state)

    if use_vol_target:
        target = al.vol_target(target, df, target_vol=0.20, vol_win_days=30, leverage_cap=2.0)

    return target


# --- Grid: 4 configs on 1d only (total backtests = 4 x 2 assets = 8, but each config
#     runs both assets via study_weights internally, so 4 study_weights calls = 4x2=8
#     asset-level backtests). Within budget.

configs = [
    dict(name="BRK04-A-BB20-2.0",    win=20, k=2.0, vol_tgt=False),
    dict(name="BRK04-B-BB20-1.5",    win=20, k=1.5, vol_tgt=False),
    dict(name="BRK04-C-BB30-2.0",    win=30, k=2.0, vol_tgt=False),
    dict(name="BRK04-D-BB20-2.0-VT", win=20, k=2.0, vol_tgt=True),
]

results = []
for cfg in configs:
    w, k, vt = cfg["win"], cfg["k"], cfg["vol_tgt"]
    fn = lambda df, _w=w, _k=k, _vt=vt: _bb_long_flat(df, win=_w, k=_k, use_vol_target=_vt)
    rep = al.study_weights(cfg["name"], fn, tfs=("1d",))
    results.append(rep)
    print(al.fmt(rep))
    print()

# Pick best config by min_asset_holdout_sharpe in best TF
def _best_score(r):
    return max(c["min_asset_holdout_sharpe"] for c in r["cells"])

best = max(results, key=_best_score)

print("\n" + "="*60)
print(f"BEST CONFIG: {best['name']}")
print(al.fmt(best))
print("JSON:", al.as_json(best))
