#!/usr/bin/env python3
"""Misst, ob ein Regressions-WINKEL-Filter die nachlaufende EMA-Richtung
verbessert (Problem: SHORT im schon gedrehten Aufwärtstrend, weil EMA12/50
nachläuft). Live-Konfig M5 + M30-EMA-Filter. Getestet wird, ob der M5- bzw.
H1-Winkel als schnellerer Wende-Detektor schlechte Signale herausfiltert.
"""
from __future__ import annotations
import sys
import MetaTrader5 as mt5
from core.analysis import calc_trend_angle
from core.wave_rec import (WaveRecommender, _atr, _ema_last,
                           _EMA_FAST, _EMA_SLOW, _N_BARS, _HTF_DEADBAND)

_LR = 14   # ANGLE_LR_BARS


class _NeutralTU:
    def snapshot(self): return {"intervals": {}}

def _ema_series(v,p):
    k=2.0/(p+1); o=[]; e=v[0]
    for i,x in enumerate(v): e=x if i==0 else x*k+e*(1-k); o.append(e)
    return o
def _atr_series(H,L,C,p=14):
    t=[0.0]
    for i in range(1,len(C)): t.append(max(H[i]-L[i],abs(H[i]-C[i-1]),abs(L[i]-C[i-1])))
    return [(sum(t[max(1,i-p+1):i+1])/max(1,len(t[max(1,i-p+1):i+1]))) if i else None for i in range(len(C))]
def _rep(name,r):
    if not r: print(f"  {name:<24} -"); return
    n=len(r); w=sum(1 for x in r if x>0)
    print(f"  {name:<24} n={n:>4}  Treffer={100*w/n:>3.0f}%  Oe-Edge={sum(r)/n:+.4f}")

def main():
    n=int(sys.argv[1]) if len(sys.argv)>1 else 8000
    K=10; dead=2.0   # Winkel-Totband um 90° (Grad)
    if not mt5.initialize(): print("init",mt5.last_error()); sys.exit(1)
    sym=None
    for c in ("SpotCrude","USOIL","WTI","XTIUSD"):
        if mt5.symbol_info(c): sym=c; break
    sym=sym or "SpotCrude"
    bars=mt5.copy_rates_from_pos(sym,mt5.TIMEFRAME_M5,0,n+_N_BARS+K+5)
    m30b=mt5.copy_rates_from_pos(sym,mt5.TIMEFRAME_M30,0,n//6+400)
    h1b =mt5.copy_rates_from_pos(sym,mt5.TIMEFRAME_H1,0,n//12+400)
    mt5.shutdown()
    if bars is None or m30b is None or h1b is None: print("Bars fehlen"); sys.exit(1)
    T=[int(b["time"]) for b in bars]; H=[float(b["high"]) for b in bars]
    L=[float(b["low"]) for b in bars]; C=[float(b["close"]) for b in bars]
    mT=[int(b["time"]) for b in m30b]; mc=[float(b["close"]) for b in m30b]
    mh=[float(b["high"]) for b in m30b]; ml=[float(b["low"]) for b in m30b]
    mEf=_ema_series(mc,_EMA_FAST); mEs=_ema_series(mc,_EMA_SLOW); mA=_atr_series(mh,ml,mc)
    hT=[int(b["time"]) for b in h1b]; hc=[float(b["close"]) for b in h1b]
    # Winkel-Serien (M5 lokal je Fenster; H1 je Bar)
    hAng=[calc_trend_angle(hc[max(0,i-_LR-2):i+1], _LR) if i>=_LR else 90.0 for i in range(len(hc))]
    def m30s(ts):
        lo,hi,idx=0,len(mT)-1,-1
        while lo<=hi:
            md=(lo+hi)//2
            if mT[md]<=ts: idx=md; lo=md+1
            else: hi=md-1
        if idx<_EMA_SLOW or mA[idx] is None or mA[idx]<=0: return 0
        d=mEf[idx]-mEs[idx]
        return 0 if abs(d)<_HTF_DEADBAND*mA[idx] else (1 if d>0 else -1)
    def h1ang(ts):
        lo,hi,idx=0,len(hT)-1,-1
        while lo<=hi:
            md=(lo+hi)//2
            if hT[md]<=ts: idx=md; lo=md+1
            else: hi=md-1
        return hAng[idx] if idx>=0 else 90.0

    w=WaveRecommender(_NeutralTU(),mt5.TIMEFRAME_M5)
    base=[]; m5_ok=[]; m5_no=[]; h1_ok=[]; h1_no=[]; gate=[]
    for i in range(_N_BARS,len(C)-K):
        wc=C[i-_N_BARS:i]; wh=H[i-_N_BARS:i]; wl=L[i-_N_BARS:i]
        atr=_atr(wh,wl,wc)
        if not atr or atr<=0: continue
        ef=_ema_last(wc,_EMA_FAST); es=_ema_last(wc,_EMA_SLOW)
        rec,_=w._build(ef,es,C[i-1],atr,"M5",5,htf_trend=m30s(T[i]))
        if rec["signal"]=="WARTEN": continue
        d=1 if rec["signal"]=="LONG" else -1
        r=(C[i+K]-C[i])*d
        base.append(r)
        a5=calc_trend_angle(C[i-_LR-2:i], _LR)   # M5-Winkel bis Signalbar
        ah=h1ang(T[i])
        a5_dis = (a5 < 90-dead) if d>0 else (a5 > 90+dead)   # Winkel klar dagegen
        ah_dis = (ah < 90-dead) if d>0 else (ah > 90+dead)
        (m5_no if a5_dis else m5_ok).append(r)
        (h1_no if ah_dis else h1_ok).append(r)
        if not ah_dis:                 # Gate: H1-Winkel NICHT klar dagegen
            gate.append(r)

    print("="*60); print(f"  Winkel-vs-EMA-Test — {sym} M5+M30  Vorlauf={K}  Totband={dead}°"); print("="*60)
    _rep("BASIS (alle)", base)
    print("-- M5-Winkel --");  _rep("M5-Winkel dafür/neutral", m5_ok); _rep("M5-Winkel klar dagegen", m5_no)
    print("-- H1-Winkel --");  _rep("H1-Winkel dafür/neutral", h1_ok); _rep("H1-Winkel klar dagegen", h1_no)
    print("-- Gate: H1-Winkel nicht dagegen --"); _rep("Gate", gate)

if __name__=="__main__":
    main()
