from fxhnt.application.funding_panel import warehouse_funding_panel
from fxhnt.application.xsfunding_replay import XsFundingReplay


def test_warehouse_funding_panel_assembles_tuple():
    closes = {"A": {1: 10.0, 2: 11.0}, "B": {1: 5.0, 2: 5.0}}
    funding = {"A": {1: 0.01, 2: 0.01}, "B": {1: -0.01, 2: -0.01}}
    panel = warehouse_funding_panel(closes, funding, qvol_fallback=1e7)
    assert panel["A"][1] == (10.0, 1e7, 0.01)
    assert panel["B"][2] == (5.0, 1e7, -0.01)


def test_warehouse_funding_panel_missing_funding_is_zero():
    closes = {"A": {1: 10.0}}
    panel = warehouse_funding_panel(closes, {}, qvol_fallback=1e7)
    assert panel["A"][1] == (10.0, 1e7, 0.0)     # no funding for that sym/day -> 0.0


def test_xsfunding_replay_longs_high_funding_shorts_low():
    # 40 days history (clears min_history=30 + lookback) ; A high funding, B low funding.
    # Domain convention (cross_sectional_funding.construction_weights "market_neutral"):
    # high funding => high robust_z score => TOP quantile => LONG (w>0);
    # low funding  => low score          => BOTTOM quantile => SHORT (w<0).
    # This is the inverse of the spec draft's comment; see report.
    closes = {s: {d: 10.0 for d in range(1, 41)} for s in ("A", "B")}
    funding = {"A": {d: 0.02 for d in range(1, 41)}, "B": {d: -0.02 for d in range(1, 41)}}
    panel = warehouse_funding_panel(closes, funding, qvol_fallback=1e7)
    w = XsFundingReplay(panel).current_weights("1970-02-10")   # epoch_day 40
    assert w.get("A", 0.0) > 0.0 and w.get("B", 0.0) < 0.0      # long high-funding A, short low-funding B
    assert abs(sum(w.values())) < 1e-9                          # market-neutral (dollar-neutral)


def test_xsfunding_replay_empty_when_no_history():
    closes = {"A": {1: 10.0}}                                   # 1 day < min_history
    panel = warehouse_funding_panel(closes, {"A": {1: 0.01}}, qvol_fallback=1e7)
    assert XsFundingReplay(panel).current_weights("1970-01-02") == {}
