#!/usr/bin/env python3
"""Verteilung der Empfehlung (Live-Konfig M5 + M30-Filter): wie oft LONG/SHORT
vs WARTEN — und WARUM WARTEN (Totband/Überdehnung/M30-Gegen-Trend)."""
from __future__ import annotations
import sys
import MetaTrader5 as mt5
from core.wave_rec import (WaveRecommender, _atr, _ema_last,
                           _EMA_FAST, _EMA_SLOW, _N_BARS, _HTF_DEADBAND)


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


def _ema_series(vals, p):
    k=2.0/(p+1); out=[]; e=vals[0]
    for i,v in enumerate(vals):
        e=v if i==0 else v*k+e*(1-k); out.append(e)
    return out

def _atr_series(H,L,C,p=14):
    trs=[0.0]
    for i in range(1,len(C)):
        trs.append(max(H[i]-L[i],abs(H[i]-C[i-1]),abs(L[i]-C[i-1])))
    return [ (sum(trs[max(1,i-p+1):i+1])/max(1,len(trs[max(1,i-p+1):i+1]))) if i else None for i in range(len(C))]


def main():
    n=int(sys.argv[1]) if len(sys.argv)>1 else 8000
    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+20)
    m30b=mt5.copy_rates_from_pos(sym,mt5.TIMEFRAME_M30,0,n//6+400)
    mt5.shutdown()
    if bars is None or m30b 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)
    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)

    w=WaveRecommender(_NeutralTU(),mt5.TIMEFRAME_M5)
    cnt={"LONG":0,"SHORT":0,"WARTEN":0}
    why={"Totband":0,"Überdehnung":0,"M30-Gegen-Trend":0,"sonst":0}
    tot=0
    for i in range(_N_BARS,len(C)):
        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]))
        sig=rec["signal"]; cnt[sig]+=1; tot+=1
        if sig=="WARTEN":
            r=(rec["reasons"] or [""])[0]
            if "kein klarer Trend" in r: why["Totband"]+=1
            elif "überdehnt" in r: why["Überdehnung"]+=1
            elif "M30" in r: why["M30-Gegen-Trend"]+=1
            else: why["sonst"]+=1
    print("="*52)
    print(f"  Signal-Verteilung — {sym} M5+M30  ({tot} Bars)")
    print("="*52)
    for k in ("LONG","SHORT","WARTEN"):
        print(f"  {k:<8} {cnt[k]:>5}  ({100*cnt[k]/tot:>4.1f} %)")
    sig_share=100*(cnt['LONG']+cnt['SHORT'])/tot
    print(f"  → Empfehlung (LONG/SHORT): {sig_share:.1f} % der Zeit")
    print("  WARTEN-Gründe:")
    wt=cnt["WARTEN"] or 1
    for k,v in why.items():
        print(f"    {k:<16} {v:>5}  ({100*v/wt:>4.1f} % der WARTEN)")


if __name__=="__main__":
    main()
