"""Gold ingest + catalog over a temp DuckDB warehouse."""
from __future__ import annotations

from fxhnt.adapters.warehouse.duckdb_feature_store import DuckDbFeatureStore
from fxhnt.application.warehouse_ingest import WarehouseIngest
from fxhnt.domain.warehouse.bar import BarRecord


def test_ingest_bars_writes_feature_rows(tmp_path) -> None:
    store = DuckDbFeatureStore(str(tmp_path / "wh.duckdb"))
    bars = [BarRecord("ES", 0, 100.0, 101.0, 99.0), BarRecord("ES", 86_400, 102.0, 103.0, 101.0)]
    n = WarehouseIngest(store).ingest_bars("ES", bars)
    assert n == 2
    rows = store.read_features("ES", features=["close", "high", "low"])
    assert [ts for ts, _ in rows] == [0, 86_400]
    assert rows[0][1] == {"close": 100.0, "high": 101.0, "low": 99.0}
    store.close()


def test_ingest_rejects_symbol_mismatch(tmp_path) -> None:
    import pytest
    store = DuckDbFeatureStore(str(tmp_path / "wh.duckdb"))
    bars = [BarRecord("ES", 0, 100.0, 101.0, 99.0), BarRecord("NQ", 0, 200.0, 201.0, 199.0)]
    with pytest.raises(ValueError):
        WarehouseIngest(store).ingest_bars("ES", bars)        # NQ bar under ES -> reject
    store.close()


def test_ingest_is_idempotent(tmp_path) -> None:
    store = DuckDbFeatureStore(str(tmp_path / "wh.duckdb"))
    bars = [BarRecord("ES", 0, 100.0, 101.0, 99.0)]
    WarehouseIngest(store).ingest_bars("ES", bars)
    WarehouseIngest(store).ingest_bars("ES", bars)          # re-ingest same range
    rows = store.read_features("ES", features=["close"])
    assert len(rows) == 1                                    # no duplication
    store.close()


def test_catalog_reports_count_and_range(tmp_path) -> None:
    store = DuckDbFeatureStore(str(tmp_path / "wh.duckdb"))
    WarehouseIngest(store).ingest_bars("ES", [BarRecord("ES", 0, 100.0, 101.0, 99.0),
                                              BarRecord("ES", 86_400, 102.0, 103.0, 101.0)])
    WarehouseIngest(store).ingest_bars("NQ", [BarRecord("NQ", 86_400, 200.0, 201.0, 199.0)])
    cat = dict((sym, (n, lo, hi)) for sym, n, lo, hi in store.catalog())
    assert cat["ES"] == (2, 0, 86_400)
    assert cat["NQ"] == (1, 86_400, 86_400)
    store.close()
