import pandas as pd
from pathlib import Path
import sys

BASE_PATH = Path(__file__).resolve().parents[2]
SRC_PATH = BASE_PATH / "src"

if str(SRC_PATH) not in sys.path:
    sys.path.append(str(SRC_PATH))

from features.spot_lag_v3 import get_model_ready_spot_lag_v3


def run_backtest(threshold):

    df = get_model_ready_spot_lag_v3().copy()

    # session filter (London + NY)
    df["hour"] = pd.to_datetime(df["datetime"]).dt.hour
    df = df[df["hour"].isin(range(7,17))]

    horizon = 48
    stop = 0.0025
    spread_cost = 0.0001

    df["future_close"] = df["close"].shift(-horizon)
    df["future_min"] = df["close"].rolling(horizon).min().shift(-horizon)
    df["future_max"] = df["close"].rolling(horizon).max().shift(-horizon)

    df = df.dropna().reset_index(drop=True)

    trades = []
    i = 0

    while i < len(df):

        row = df.iloc[i]

        signal = 0
        if row["lag_zscore_24h_v3"] >= threshold:
            signal = 1
        elif row["lag_zscore_24h_v3"] <= -threshold:
            signal = -1

        if signal == 0:
            i += 1
            continue

        entry = row["close"]

        if signal == 1:
            stop_hit = (row["future_min"] - entry) / entry < -stop
            ret = row["future_close"] / entry - 1
            if stop_hit:
                ret = -stop
        else:
            stop_hit = (row["future_max"] - entry) / entry > stop
            ret = -(row["future_close"] / entry - 1)
            if stop_hit:
                ret = -stop

        ret -= spread_cost
        trades.append(ret)

        i += horizon

    trades = pd.Series(trades)

    if len(trades) == 0:
        return None

    equity = (1 + trades).cumprod()
    peak = equity.cummax()
    dd = equity / peak - 1

    return {
        "threshold": threshold,
        "trades": len(trades),
        "avg_return": trades.mean(),
        "win_rate": (trades > 0).mean(),
        "final_equity": equity.iloc[-1],
        "max_dd": dd.min(),
    }


def run_test():

    thresholds = [2.0,2.25,2.5,2.75,3.0]

    results = []

    for t in thresholds:
        res = run_backtest(t)
        if res:
            results.append(res)

    df = pd.DataFrame(results)

    print("\n=== SIGNAL STRENGTH FILTER TEST ===\n")
    print(df.to_string(index=False))


if __name__ == "__main__":
    run_test()