import datetime as dt

from fxhnt.adapters.persistence.forward_nav import ForwardNavRepo
from fxhnt.application.bybit_exec_record import record_bybit_exec_track


def test_records_observed_return_and_carries_basis(tmp_path):
    repo = ForwardNavRepo(f"sqlite:///{tmp_path/'c.db'}")
    repo.migrate()
    at = dt.datetime(2026, 7, 10)
    # inception: exec_return None -> a forward_record is booked with no return row, basis is carried.
    record_bybit_exec_track(repo, None, {"BTCUSDT": 1.0}, {"BTCUSDT": 100.0}, 10_000.0, 1_700_000_000_000,
                            "2026-07-10", at)
    st = repo.get_book_state("bybit_4edge_exec_pos")
    assert st["envelope"] == 10_000.0
    assert st["positions"] == {"BTCUSDT": 1.0}
    assert st["funding_cursor_ts"] == 1_700_000_000_000
    # second run books a real return.
    record_bybit_exec_track(repo, 0.01, {"BTCUSDT": 2.0}, {"BTCUSDT": 101.0}, 10_000.0, 1_700_100_000_000,
                            "2026-07-11", dt.datetime(2026, 7, 11))
    hist = repo.nav_history("bybit_4edge_exec")
    assert any(abs(r.ret - 0.01) < 1e-9 for r in hist)
    assert repo.get_book_state("bybit_4edge_exec_pos")["positions"] == {"BTCUSDT": 2.0}
