import datetime as dt

from fxhnt.adapters.persistence.paper_repo import PaperRepo
from fxhnt.domain.paper import Position, Trade


def test_nav_history_and_lookups():
    repo = PaperRepo("sqlite://")
    repo.migrate()
    at = dt.datetime(2026, 6, 21, tzinfo=dt.UTC)
    repo.upsert_nav("2026-06-20", capital=100000.0, realized=0.0, unrealized=10.0, equity=100010.0, at=at)
    repo.upsert_nav("2026-06-21", capital=100000.0, realized=5.0, unrealized=20.0, equity=100025.0, at=at)
    repo.upsert_nav("2026-06-21", capital=100000.0, realized=5.0, unrealized=25.0, equity=100030.0, at=at)  # idempotent overwrite
    hist = repo.nav_history()
    assert [h.run_date for h in hist] == ["2026-06-20", "2026-06-21"]   # ascending, deduped
    assert hist[-1].equity == 100030.0
    assert hist[-1].realized == 5.0
    assert hist[-1].unrealized == 25.0


def test_positions_at_and_trades_on():
    repo = PaperRepo("sqlite://")
    repo.migrate()
    at = dt.datetime(2026, 6, 21, tzinfo=dt.UTC)
    repo.replace_positions("2026-06-20",
                           [Position("s", "BTCUSDT", 1.0, 100.0, "2026-06-20")],
                           weight_by_sleeve={"s": 1.0}, at=at)
    repo.replace_positions("2026-06-21",
                           [Position("s", "BTCUSDT", 2.0, 110.0, "2026-06-21")],
                           weight_by_sleeve={"s": 1.0}, at=at)
    repo.record_trades([Trade("2026-06-20T00:00:00Z", "s", "BTCUSDT", "BUY", 1.0, 100.0, "rebalance")],
                       at=at, run_date="2026-06-20")
    repo.record_trades([Trade("2026-06-21T00:00:00Z", "s", "BTCUSDT", "BUY", 1.0, 110.0, "rebalance")],
                       at=at, run_date="2026-06-21")

    pos = repo.positions_at("2026-06-20")
    assert [p.qty for p in pos] == [1.0]
    assert pos[0].entry_price == 100.0

    trades = repo.trades_on("2026-06-21")
    assert len(trades) == 1
    assert trades[0].price == 110.0
