"""Resta qualche candidato? — passa i contendenti promettenti piu' forti del sweep
(trend non-TSMOM, overlay DVOL, rotazione cross-asset) attraverso il gate MARGINALE vs TP01.
Run: uv run python scripts/research/alt/marginal_remaining.py
"""
import sys
sys.path.insert(0, "/opt/docker/PythagorasGoal/scripts/research/alt")
import numpy as np
import pandas as pd

import altlib as al


def tsmom_dir(df):
    c = df["close"].values.astype(float); bpd = al.bars_per_day(df); d = np.zeros(len(c))
    for h in (30 * bpd, 90 * bpd, 180 * bpd):
        s = np.full(len(c), np.nan); s[h:] = np.sign(c[h:] / c[:-h] - 1.0); d += np.nan_to_num(s)
    return np.clip(np.sign(d), 0, None)


def wma(x, n):
    w = np.arange(1, n + 1)
    return pd.Series(x).rolling(n).apply(lambda v: np.dot(v, w) / w.sum(), raw=True).values


# --- TRD10 Vortex(14) long-flat ---
def trd10(df):
    h = df["high"].values.astype(float); l = df["low"].values.astype(float); c = df["close"].values.astype(float)
    pc = np.roll(c, 1); pc[0] = c[0]; ph = np.roll(h, 1); ph[0] = h[0]; pl = np.roll(l, 1); pl[0] = l[0]
    tr = np.maximum(h - l, np.maximum(np.abs(h - pc), np.abs(l - pc)))
    n = 14; strn = pd.Series(tr).rolling(n).sum().values
    vip = pd.Series(np.abs(h - pl)).rolling(n).sum().values / strn
    vim = pd.Series(np.abs(l - ph)).rolling(n).sum().values / strn
    d = np.where(np.isnan(vip), 0.0, np.where(vip > vim, 1.0, 0.0))
    return al.vol_target(d, df, 0.20, 30, 2.0)


# --- TRD08 Hull MA slope ---
def trd08(df):
    c = df["close"].values.astype(float)
    h = wma(2 * wma(c, 27) - wma(c, 55), 7)   # HMA(55)
    slope = np.zeros(len(h)); slope[1:] = h[1:] - h[:-1]
    d = np.where(slope > 0, 1.0, 0.0); d[np.isnan(h)] = 0.0
    return al.vol_target(d, df, 0.20, 30, 2.0)


# --- TRD07 Kaufman AMA cross ---
def kama(c, n=10, fast=2, slow=30):
    c = np.asarray(c, float); L = len(c); out = np.copy(c)
    fsc, ssc = 2 / (fast + 1), 2 / (slow + 1)
    vol = pd.Series(np.abs(np.diff(c, prepend=c[0]))).rolling(n).sum().values
    change = np.full(L, np.nan); change[n:] = np.abs(c[n:] - c[:-n])
    sc = (np.where(vol > 0, change / vol, 0.0) * (fsc - ssc) + ssc) ** 2
    for i in range(1, L):
        out[i] = out[i - 1] if np.isnan(sc[i]) else out[i - 1] + sc[i] * (c[i] - out[i - 1])
    return out


def trd07(df):
    c = df["close"].values.astype(float); k = kama(c)
    slope = np.zeros(len(k)); slope[1:] = k[1:] - k[:-1]
    d = np.where((c > k) & (slope > 0), 1.0, 0.0)
    return al.vol_target(d, df, 0.20, 30, 2.0)


# --- VOL08 realized-vol term-structure overlay on TSMOM ---
def vol08(df):
    c = df["close"].values.astype(float); bpd = al.bars_per_day(df); r = al.simple_returns(c)
    sv = al.realized_vol(r, 5 * bpd, bpd * 365.25); lv = al.realized_vol(r, 30 * bpd, bpd * 365.25)
    ratio = sv / lv; d = tsmom_dir(df)
    d = np.where((ratio < 1.0) | np.isnan(ratio), d, 0.0)
    return al.vol_target(d, df, 0.20, 30, 2.0)


# --- VOL11 DVOL kill-switch on TSMOM (df, asset) ---
def vol11(df, asset):
    d = tsmom_dir(df); dv = pd.Series(al.dvol(df, asset))
    thr = dv.expanding(min_periods=30).quantile(0.80)
    kill = (~dv.isna()) & (~thr.isna()) & (dv > thr)
    d = np.where(kill.values, 0.0, d)
    return al.vol_target(d, df, 0.20, 30, 2.0)


# --- XAS09/03 cross-asset rotation (hold the stronger of BTC/ETH; dual=flat if both neg) ---
def rotation_daily(lb=90, dual=True):
    R, M, V = {}, {}, {}
    for a in ("BTC", "ETH"):
        df = al.get(a, "1d"); c = df["close"].values.astype(float)
        idx = pd.DatetimeIndex(pd.to_datetime(df["datetime"], utc=True))
        mom = np.full(len(c), np.nan); mom[lb:] = c[lb:] / c[:-lb] - 1.0
        R[a] = pd.Series(al.simple_returns(c), index=idx)
        M[a] = pd.Series(mom, index=idx)
        V[a] = pd.Series(al.vol_target(np.ones(len(c)), df, 0.20, 30, 2.0), index=idx)
    R = pd.concat(R, axis=1, join="inner"); M = pd.concat(M, axis=1, join="inner").shift(1)
    V = pd.concat(V, axis=1, join="inner").shift(1)
    out = np.zeros(len(R))
    for t in range(len(R)):
        mrow = M.iloc[t]
        if mrow.isna().all():
            continue
        best = mrow.idxmax()
        if dual and mrow[best] <= 0:
            continue
        pos = V.iloc[t][best]
        out[t] = (0.0 if np.isnan(pos) else pos) * R.iloc[t][best]
    return pd.Series(out, index=R.index)


SINGLE = [("TRD10 Vortex", trd10), ("TRD08 Hull MA", trd08), ("TRD07 KAMA", trd07),
          ("VOL08 RV term-struct", vol08), ("VOL11 DVOL kill-switch", vol11)]

print("=" * 90)
print("RESTA QUALCHE CANDIDATO? — gate marginale vs TP01 sui contendenti piu' forti")
print("=" * 90)
rows = []
for name, fn in SINGLE:
    rep = al.study_marginal(name, fn, tf="1d")
    m = rep["marginal"]
    print(al.fmt_marginal(rep))
    print()
    rows.append((name, rep["abs_grade"], rep["marginal_verdict"], rep["earns_slot"],
                 m.get("corr_hold"), m["blends"]["w25"].get("uplift_hold")))

# cross-asset rotations (built directly, scored marginally)
for name, dual in [("XAS09 dual-momentum", True), ("XAS03 RS rotation", False)]:
    m = al.marginal_vs_tp01(rotation_daily(90, dual))
    v = m["marginal_verdict"]
    print(al.fmt_marginal({"name": name, "abs_grade": "n/a", "marginal_verdict": v,
                           "earns_slot": v == "ADDS", "marginal": m}))
    print()
    rows.append((name, "n/a", v, v == "ADDS", m.get("corr_hold"), m["blends"]["w25"].get("uplift_hold")))

print("=" * 90)
print(f"{'candidato':<26s}{'abs':>7s}{'marginale':>12s}{'slot':>7s}{'corr_hold':>11s}{'upliftH_w25':>13s}")
for n, ag, mv, es, ch, uh in rows:
    print(f"{n:<26s}{ag:>7s}{mv:>12s}{str(es):>7s}{str(ch):>11s}{str(uh):>13s}")
print("\n(ADDS+slot=True => candidato vivo; tutto il resto => morto/ridondante)")
