from typing import List, Tuple, Dict, Any
import operator

OPS = {
    ">": operator.gt,
    ">=": operator.ge,
    "<": operator.lt,
    "<=": operator.le,
    "==": operator.eq,
    "!=": operator.ne,
}

def apply_filters(row: Dict[str, Any], filters: List[Tuple[str,str,str]]) -> bool:
    """
    filters = [("Preis", ">=", "5"), ("AvgVol20", ">=", "1000000")]
    Map Feldnamen -> row-Keys nach Bedarf.
    """
    alias = {
        "Preis": "price",
        "RVOL": "rvol",
        "ATR%": "atrp",
        "Score": "score",
        "Trend": "trend",
        "AvgVol20": "avgvol20", # optional, wenn verfügbar
    }
    for field, op, value in filters:
        key = alias.get(field, field)
        if key not in row:
            return False
        left = row[key]
        right = value
        try:
            # Zahlen normalisieren (1’000’000 / 1,000,000 -> 1000000)
            right = str(right).replace("’","").replace(",","").replace(" ","")
            if isinstance(left, (int,float)):
                right = float(right)
        except Exception:
            pass
        fn = OPS.get(op, None)
        if fn is None:
            return False
        try:
            if not fn(left, right):
                return False
        except Exception:
            return False
    return True
