#!/usr/bin/env python3
import os, json, math
import datetime as dt

ROOT = os.path.expanduser("~/kleiner")
INTRA = os.path.join(ROOT, "data", "intraday")
OUT = os.path.join(ROOT, "data", "live_scan", "signals_live.json")

def ema(values, period):
    if not values:
        return []
    k = 2.0 / (period + 1.0)
    out = []
    e = values[0]
    out.append(e)
    for v in values[1:]:
        e = (v * k) + (e * (1 - k))
        out.append(e)
    return out

def atr_pct(highs, lows, closes, period=14):
    # einfache ATR% auf Basis True Range
    if len(closes) < period + 2:
        return None
    trs = []
    for i in range(1, len(closes)):
        h = highs[i]
        l = lows[i]
        pc = closes[i-1]
        tr = max(h - l, abs(h - pc), abs(l - pc))
        trs.append(tr)
    if len(trs) < period:
        return None
    atr = sum(trs[-period:]) / period
    last = closes[-1]
    if last <= 0:
        return None
    return (atr / last) * 100.0

def load_series(path):
    with open(path, "r", encoding="utf-8") as f:
        arr = json.load(f)
    # arr: [{"ts","o","h","l","c","v"}, ...]
    if not isinstance(arr, list) or len(arr) < 60:
        return None
    closes = [float(x["c"]) for x in arr]
    highs  = [float(x["h"]) for x in arr]
    lows   = [float(x["l"]) for x in arr]
    vols   = [float(x.get("v",0)) for x in arr]
    last_ts = arr[-1]["ts"]
    return closes, highs, lows, vols, last_ts

def make_signal(ticker, closes, highs, lows, vols, last_ts):
    e20 = ema(closes, 20)
    e50 = ema(closes, 50)

    c = closes[-1]
    c1 = closes[-2]
    c5 = closes[-6] if len(closes) >= 6 else closes[0]

    atrp = atr_pct(highs, lows, closes, 14)  # ATR%
    if atrp is None:
        return None

    # Trendrichtung: EMA20 vs EMA50
    trend = "LONG" if e20[-1] > e50[-1] else "SHORT"

    # kleiner Momentum-Check
    mom = (c - c5) / c5 * 100.0 if c5 else 0.0

    # sehr simple Signalbedingungen (wir härten später):
    # LONG: Kurs über EMA20, Momentum positiv
    # SHORT: Kurs unter EMA20, Momentum negativ
    if trend == "LONG":
        if not (c > e20[-1] and mom > 0):
            return None
    else:
        if not (c < e20[-1] and mom < 0):
            return None

    # SL/TP Logik (einfach): SL = 1.2 * ATR% , TP1 = 1.8 * ATR% , TP2 = 2.6 * ATR%
    sl_pct  = max(1.2 * atrp, 0.6)
    tp1_pct = max(1.8 * atrp, 1.0)
    tp2_pct = max(2.6 * atrp, 1.5)

    if trend == "LONG":
        entry = c
        sl = entry * (1 - sl_pct/100.0)
        tp1 = entry * (1 + tp1_pct/100.0)
        tp2 = entry * (1 + tp2_pct/100.0)
    else:
        entry = c
        sl = entry * (1 + sl_pct/100.0)
        tp1 = entry * (1 - tp1_pct/100.0)
        tp2 = entry * (1 - tp2_pct/100.0)

    risk = abs(entry - sl)
    reward = abs(tp1 - entry)
    crv = (reward / risk) if risk > 0 else 0.0

    # Score (einfach): Trend + Momentum + ATR-Fit + CRV
    score = 60.0
    score += min(15.0, abs(mom) * 2.0)       # max +15
    score += 10.0 if (2.0 <= atrp <= 8.0) else 0.0
    score += 15.0 if crv >= 1.2 else 0.0
    score = max(0.0, min(99.0, score))

    # Gültig bis: 90 Minuten ab jetzt (CH egal, wir speichern UTC)
    now = dt.datetime.utcnow()
    valid_until = (now + dt.timedelta(minutes=90)).replace(microsecond=0).isoformat() + "Z"

    comment = f"Trend {trend} | Mom {mom:.2f}% | ATR% {atrp:.2f}"

    return {
        "ticker": ticker,
        "richtung": "Long" if trend == "LONG" else "Short",
        "entry": round(entry, 4),
        "sl": round(sl, 4),
        "tp1": round(tp1, 4),
        "tp2": round(tp2, 4),
        "score": round(score, 1),
        "crv": round(crv, 2),
        "status": "aktiv",
        "gültig_bis": valid_until,
        "last_bar_utc": last_ts,
        "comment": comment
    }

def main():
    os.makedirs(os.path.dirname(OUT), exist_ok=True)

    signals = []
    for fn in sorted(os.listdir(INTRA)):
        if not fn.endswith("_5m.json"):
            continue
        ticker = fn.replace("_5m.json","").upper().strip()
        path = os.path.join(INTRA, fn)
        series = load_series(path)
        if not series:
            continue
        closes, highs, lows, vols, last_ts = series
        sig = make_signal(ticker, closes, highs, lows, vols, last_ts)
        if sig:
            signals.append(sig)

    out = {
        "last_update_utc": dt.datetime.utcnow().replace(microsecond=0).isoformat()+"Z",
        "market_mode": None,
        "signals": signals
    }

    tmp = OUT + ".tmp"
    with open(tmp, "w", encoding="utf-8") as f:
        json.dump(out, f, ensure_ascii=False, indent=2)
    os.replace(tmp, OUT)

    print("Wrote:", OUT)
    print("Signals:", len(signals))

if __name__ == "__main__":
    main()
