"""DuckDB store round-trips high/low and migrates a pre-existing close-only DB."""
from __future__ import annotations

import numpy as np

from fxhnt.adapters.persistence.analytical import DuckDbAnalyticalStore
from fxhnt.domain.models import AssetClass, Market, PriceSeries

_M = Market(symbol="ES", asset_class=AssetClass.FUTURE)


def test_save_load_round_trips_high_low(tmp_path) -> None:
    store = DuckDbAnalyticalStore(str(tmp_path / "a.duckdb"))
    ps = PriceSeries(market=_M, dates=("2020-01-01", "2020-01-02"),
                     close=np.array([100.0, 101.0]), high=np.array([101.0, 102.0]),
                     low=np.array([99.0, 100.0]))
    store.save_prices(ps)
    got = store.load_prices(_M)
    assert got is not None
    assert list(got.high) == [101.0, 102.0]
    assert list(got.low) == [99.0, 100.0]
    store.close()


def test_pre_migration_rows_load_with_high_low_equal_close(tmp_path) -> None:
    import duckdb
    db = str(tmp_path / "old.duckdb")
    con = duckdb.connect(db)                       # simulate an OLD close-only schema + row
    con.execute("CREATE TABLE prices (symbol VARCHAR, asset_class VARCHAR, date VARCHAR, close DOUBLE)")
    con.execute("INSERT INTO prices VALUES ('ES', 'future', '2019-12-31', 95.0)")
    con.close()
    store = DuckDbAnalyticalStore(db)              # __init__ migrates (ADD COLUMN IF NOT EXISTS)
    got = store.load_prices(_M)
    assert got is not None
    assert list(got.close) == [95.0]
    assert list(got.high) == [95.0] and list(got.low) == [95.0]   # NULL high/low -> close
    store.close()
