#!/usr/bin/env python3
"""Rekonstruiert die heutigen Empfehlungen (echte _build-Logik) über die M5-Bars
und korreliert sie mit dem Kurs + den heutigen Trades. Zeigt Signal-Wechsel,
Trefferquote und Auffälligkeiten."""
import datetime as dt
import sqlite3
import MetaTrader5 as mt5
from core.wave_rec import (WaveRecommender, _atr, _ema_last, _EMA_FAST, _EMA_SLOW,
                           _N_BARS, _HTF_DEADBAND, _ANGLE_LR)
from core.analysis import calc_trend_angle

OFF = 3600  # Broker(UTC+3)→Berlin(UTC+2, Juni): epoch-1h


class _TU:
    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 bt(ts): return dt.datetime.utcfromtimestamp(ts-OFF)  # Berlin

mt5.initialize()
sym=None
for c in ("SpotCrude","USOIL","WTI","XTIUSD"):
    if mt5.symbol_info(c): sym=c; break
bars=mt5.copy_rates_from_pos(sym, mt5.TIMEFRAME_M5, 0, 700)
m30=mt5.copy_rates_from_pos(sym, mt5.TIMEFRAME_M30, 0, 200)
mt5.shutdown()
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 m30]; mc=[float(b["close"]) for b in m30]
mh=[float(b["high"]) for b in m30]; ml=[float(b["low"]) for b in m30]
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)

today = bt(T[-1]).date()
w=WaveRecommender(_TU(), mt5.TIMEFRAME_M5)
rows=[]  # (i, berlin, close, signal, conf, reason)
K=6
for i in range(_N_BARS, len(C)):
    b=bt(T[i])
    if b.date()!=today: continue
    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)
    ang=calc_trend_angle(C[i-_ANGLE_LR-2:i],_ANGLE_LR)
    rec,_=w._build(ef,es,C[i-1],atr,"M5",5,htf_trend=m30s(T[i]),
                   angle=ang,hour=b.hour)
    fwd=(C[i+K]-C[i]) if i+K<len(C) else None
    rows.append((i,b,C[i],rec["signal"],rec["conf_pct"],(rec["reasons"] or [""])[0],fwd))

# Signal-Wechsel
print("="*72); print(f"  Heutige Empfehlung vs Kurs — {sym} {today}  (M5, Live-Logik)"); print("="*72)
print("Signal-WECHSEL (Zeit Berlin · Kurs · Signal · conf · Grund):")
prev=None
for (i,b,px,sig,cf,rs,fwd) in rows:
    if sig!=prev:
        print(f"  {b.strftime('%H:%M')}  {px:7.3f}  {sig:6} {cf:>3}  {rs[:54]}")
        prev=sig
# Trefferquote der Nicht-WARTEN-Signale (Vorlauf 6 Bars)
ev=[(sig,fwd) for (_,_,_,sig,_,_,fwd) in rows if sig in ("LONG","SHORT") and fwd is not None]
if ev:
    win=sum(1 for s,f in ev if (f>0)==(s=="LONG"))
    edge=sum((f if s=="LONG" else -f) for s,f in ev)/len(ev)
    nL=sum(1 for s,_ in ev if s=="LONG"); nS=len(ev)-nL
    print(f"\nSignale heute: {len(ev)} (LONG {nL} / SHORT {nS}) · Treffer {100*win/len(ev):.0f}% · Oe-Edge {edge:+.4f}")
warten=sum(1 for (_,_,_,s,_,_,_) in rows if s=="WARTEN")
print(f"WARTEN-Bars: {warten}/{len(rows)} ({100*warten/max(1,len(rows)):.0f}%)")

# Trades heute
print("\nTrades heute (DB):")
c=sqlite3.connect('oil_widget_history.db'); c.row_factory=sqlite3.Row
t0=dt.datetime.now().replace(hour=0,minute=0,second=0,microsecond=0).timestamp()
for r in c.execute('SELECT entry_time,exit_time,direction,entry_price,exit_price,pnl,closed_by FROM trades WHERE exit_time>=? ORDER BY exit_time',(t0,)):
    print(f"  {dt.datetime.fromtimestamp(r['entry_time']).strftime('%H:%M')}→{dt.datetime.fromtimestamp(r['exit_time']).strftime('%H:%M')} "
          f"{r['direction']:4} {r['entry_price']:.3f}→{r['exit_price']:.3f}  pnl {r['pnl']:+.2f}  {r['closed_by']}")
