"""Replayable cross-sectional funding sleeve (a PositionSource for the paper backfill/snapshot). Runs the
SAME pure domain pipeline as live xsfunding (eligible -> funding_score -> construction_weights) but sourced
from the warehouse funding panel instead of a live snapshot. mode='market_neutral' (the backtest-validated
mode; the live 'executable' mode needs a borrowable set we can't reconstruct historically). Causal:
eligible_asof/funding_score use only data <= asof_day."""
from __future__ import annotations

import datetime as dt

from fxhnt.domain.cross_sectional_funding import (
    Panel, construction_weights, eligible_asof, funding_score,
)


class XsFundingReplay:
    return_mode = "carry"  # P&L is funding carry, not price-MTM (paper book books sleeve_daily_carry)

    def __init__(self, panel: Panel, *, min_qvol: float = 1e6, min_history: int = 30,
                 lookback_days: int = 7, quantile: float = 0.2) -> None:
        self._p = panel
        self._minq, self._minh, self._lb, self._q = min_qvol, min_history, lookback_days, quantile

    def current_weights(self, as_of: str) -> dict[str, float]:
        day = (dt.date.fromisoformat(as_of) - dt.date(1970, 1, 1)).days
        elig = eligible_asof(self._p, day, min_qvol=self._minq, min_history=self._minh)
        if not elig:
            return {}
        scores = funding_score(self._p, elig, day, lookback_days=self._lb)
        return construction_weights(scores, "market_neutral", quantile=self._q)
