import pandas as pd
import numpy as np
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 ingestion.price_loader_15m import load_eurusd_15m


def compute_atr(df, period=96):
    """
    96 bars = 24h on 15m data
    """
    df = df.copy()

    df["prev_close"] = df["close"].shift(1)

    tr1 = df["high"] - df["low"]
    tr2 = abs(df["high"] - df["prev_close"])
    tr3 = abs(df["low"] - df["prev_close"])

    df["tr"] = np.maximum(tr1, np.maximum(tr2, tr3))
    df["atr"] = df["tr"].rolling(period).mean()

    return df


def run_vol_filter_test():

    df = load_eurusd_15m().copy()
    df = df.sort_values("datetime").reset_index(drop=True)

    df = compute_atr(df)

    median_atr = df["atr"].median()

    thresholds = [1.0, 1.25, 1.5, 1.75, 2.0]

    results = []

    for threshold in thresholds:

        allowed = df[df["atr"] <= median_atr * threshold].copy()

        trades = len(allowed)

        # simple proxy return model for testing
        returns = allowed["close"].pct_change().dropna()

        avg_return = returns.mean()
        win_rate = (returns > 0).mean()

        equity = (1 + returns).cumprod()
        final_equity = equity.iloc[-1]

        peak = equity.cummax()
        dd = equity / peak - 1
        max_dd = dd.min()

        results.append({
            "threshold": threshold,
            "bars": trades,
            "win_rate": win_rate,
            "avg_return": avg_return,
            "final_equity": final_equity,
            "max_dd": max_dd
        })

    results = pd.DataFrame(results)

    print("\n=== VOLATILITY FILTER TEST V1 ===\n")
    print(results)

    best_equity = results.sort_values("final_equity", ascending=False).iloc[0]
    best_dd = results.sort_values("max_dd", ascending=False).iloc[0]

    print("\nBest by equity:")
    print(best_equity)

    print("\nBest by drawdown:")
    print(best_dd)


if __name__ == "__main__":
    run_vol_filter_test()