"""Live-booking unlock-short ForwardStrategy — first-run freeze, forward booking, market-neutral P&L.
Uses a FAKE live client (no network)."""
from fxhnt.application.forward_tracker import ForwardTracker
from fxhnt.application.unlock_short_strategy import UnlockShortForward


class _FakeLive:
    """Scripted snapshots keyed by asof_day; returns window + prices + btc like UnlockCalendarLive."""
    def __init__(self, script):
        self._script = script

    def snapshot(self, prev_names, asof_day):
        return self._script[asof_day]


def test_first_run_freezes_then_books_forward(tmp_path):
    # day 100: a big cliff for FOO in window -> seed short. day 101: FOO fell 10%, BTC flat -> short profits.
    import datetime as dt
    base = dt.date.today()
    d100, d101 = base.isoformat(), (base + dt.timedelta(days=1)).isoformat()
    e0 = (base - dt.date(1970, 1, 1)).days
    e1 = e0 + 1
    cliff = e0 + 8
    script = {
        e0: {"window": {"FOO": {"cliff_day": cliff, "n": 1e7, "perp": 10.0, "funding": 0.0, "qvol": 5e7}},
             "prices": {"FOO": (10.0, 0.0)}, "btc": 50000.0},
        e1: {"window": {"FOO": {"cliff_day": cliff, "n": 1e7, "perp": 9.0, "funding": 0.0, "qvol": 5e7}},
             "prices": {"FOO": (9.0, 0.0)}, "btc": 50000.0},
    }
    p = str(tmp_path / "u.json")
    clk = {"d": d100}
    strat = UnlockShortForward(_FakeLive(script), clock=lambda: clk["d"])
    st0 = ForwardTracker(strat, p).step()
    assert st0.forward_days == 0                      # freeze: seed, book nothing
    clk["d"] = d101
    st1 = ForwardTracker(strat, p).step()
    assert st1.forward_days == 1                      # books the next day
    # FOO -10%, market-neutral short -> ~+10% on the (gross-1) book, minus tiny turnover cost
    assert st1.forward_return_pct > 8.0


def test_shock_filter_excludes_tiny_unlocks(tmp_path):
    import datetime as dt
    d = (dt.date(1970, 1, 1) + dt.timedelta(days=100)).isoformat()
    # unlock notional = 1e3 * 1.0 = $1k vs $5e7 qvol -> shock ~0 -> excluded
    script = {100: {"window": {"TINY": {"cliff_day": 105, "n": 1e3, "perp": 1.0, "funding": 0.0, "qvol": 5e7}},
                    "prices": {}, "btc": 50000.0}}
    strat = UnlockShortForward(_FakeLive(script), clock=lambda: d)
    rows, extra = strat.advance(None, {})
    assert extra["positions"] == {}                  # tiny unlock filtered out
