from typing import List, Any, Dict
from ..core.base import Transformer


class CalculateTransformer(Transformer):
    def __init__(self, add: Dict[str, List[str]] | None = None, calculations: List[Dict[str, str]] | None = None) -> None:
        self.add = add or {}
        self.calculations = calculations or []

    def transform_batch(self, batch: List[Any]) -> List[Any]:
        out: List[Any] = []
        for item in batch:
            if isinstance(item, dict):
                # Legacy add support
                if self.add:
                    for new_key, keys in self.add.items():
                        total = 0.0
                        for k in keys:
                            v = item.get(k)
                            if isinstance(v, (int, float)):
                                total += float(v)
                        item[new_key] = total
                
                # New calculations support
                if self.calculations:
                    for calc in self.calculations:
                        field = calc.get("field")
                        expression = calc.get("expression")
                        if field and expression:
                            try:
                                # Use item as context for evaluation
                                item[field] = eval(expression, {"__builtins__": {}}, item)
                            except Exception:
                                # Ignore calculation errors (e.g. missing fields)
                                pass
                out.append(item)
            else:
                out.append(item)
        return out
