"""Test forward_record append-only log and book-state persistence."""
import datetime as dt

from fxhnt.adapters.persistence.forward_nav import ForwardNavRepo


def _repo(tmp_path):
    repo = ForwardNavRepo(f"sqlite:///{tmp_path}/rec.db")
    repo.migrate()
    return repo


def test_append_is_idempotent_per_date(tmp_path):
    repo = _repo(tmp_path)
    at = dt.datetime(2026, 7, 8, 23, 30)
    repo.append_record("xsfunding", "2026-07-08", 0.001, at)
    repo.append_record("xsfunding", "2026-07-08", 0.001, at)   # same date re-run → no double append
    assert repo.record_series("xsfunding") == [("2026-07-08", 0.001)]


def test_record_series_filters_since(tmp_path):
    repo = _repo(tmp_path)
    at = dt.datetime(2026, 7, 8, 23, 30)
    for d, r in [("2026-07-06", 0.001), ("2026-07-07", 0.002), ("2026-07-08", 0.003)]:
        repo.append_record("xsfunding", d, r, at)
    assert repo.record_series("xsfunding", since="2026-07-07") == [("2026-07-07", 0.002), ("2026-07-08", 0.003)]


def test_record_series_sorts_ascending_regardless_of_insert_order(tmp_path):
    repo = _repo(tmp_path)
    at = dt.datetime(2026, 7, 8, 23, 30)
    # insert OUT of chronological order — a dropped/incorrect order_by must fail this
    for d, r in [("2026-07-08", 0.003), ("2026-07-06", 0.001), ("2026-07-07", 0.002)]:
        repo.append_record("xsfunding", d, r, at)
    assert repo.record_series("xsfunding") == [
        ("2026-07-06", 0.001), ("2026-07-07", 0.002), ("2026-07-08", 0.003)]


def test_append_record_rejects_malformed_date(tmp_path):
    import pytest
    repo = _repo(tmp_path)
    with pytest.raises(ValueError):
        repo.append_record("x", "2026-7-8", 0.0, dt.datetime(2026, 7, 8))


def test_book_state_round_trip(tmp_path):
    repo = _repo(tmp_path)
    at = dt.datetime(2026, 7, 8, 23, 30)
    assert repo.get_book_state("xsfunding") == {}
    repo.set_book_state("xsfunding", {"positions": {"BTCUSDT": 0.5}}, at)
    assert repo.get_book_state("xsfunding") == {"positions": {"BTCUSDT": 0.5}}
