import datetime as dt
from fxhnt.adapters.persistence.paper_repo import PaperRepo
from fxhnt.domain.paper import Position

def _repo():
    r = PaperRepo("sqlite://"); r.migrate(); return r

def test_replace_and_read_shadow_before():
    r = _repo(); at = dt.datetime(2026, 1, 2, tzinfo=dt.UTC)
    r.replace_shadow_positions("2026-01-01",
        [Position("ts", "BTCUSDT", 0.01, 100.0, "2026-01-01")], at=at)
    r.replace_shadow_positions("2026-01-02",
        [Position("ts", "BTCUSDT", 0.02, 110.0, "2026-01-02")], at=at)
    before2 = r.shadow_positions_before("2026-01-02")
    assert len(before2) == 1 and before2[0].entry_price == 100.0    # the prior date's shadow book
    assert r.shadow_positions_before("2026-01-01") == []            # nothing strictly before

def test_replace_is_idempotent_per_run_date():
    r = _repo(); at = dt.datetime(2026, 1, 2, tzinfo=dt.UTC)
    r.replace_shadow_positions("2026-01-01", [Position("ts", "BTCUSDT", 0.01, 100.0, "2026-01-01")], at=at)
    r.replace_shadow_positions("2026-01-01", [Position("ts", "ETHUSDT", 0.5, 50.0, "2026-01-01")], at=at)
    before = r.shadow_positions_before("2026-01-02")
    assert len(before) == 1 and before[0].symbol == "ETHUSDT"        # replaced, not appended
