"""WarehouseIngest — the gold write step. Turns BarRecords into point-in-time feature rows and persists
them to the warehouse (idempotent on the (symbol, ts-range) being written)."""
from __future__ import annotations

from fxhnt.domain.warehouse.bar import BarRecord
from fxhnt.ports.warehouse import FeatureStore


class WarehouseIngest:
    def __init__(self, store: FeatureStore) -> None:
        self._store = store

    def ingest_bars(self, symbol: str, bars: list[BarRecord]) -> int:
        mismatched = sorted({b.symbol for b in bars if b.symbol != symbol})
        if mismatched:
            raise ValueError(f"ingest_bars({symbol!r}) received bars for other symbols: {mismatched}")
        self._store.write_features(symbol, [b.as_feature_row() for b in bars])
        return len(bars)

    def ingest_bars_bulk(self, symbol_to_bars: dict[str, list[BarRecord]]) -> int:
        """Ingest many symbols in ONE warehouse transaction (bulk fast path). Returns total bars."""
        items = [(sym, [b.as_feature_row() for b in bars]) for sym, bars in symbol_to_bars.items()]
        self._store.write_features_bulk(items)
        return sum(len(bars) for bars in symbol_to_bars.values())
