"""Marginal contribution of a candidate sleeve to the book: the increase in annualized Sharpe from blending
it in at `weight`. Positive = the sleeve improves the risk-adjusted book (the selection objective). NaN if
the series are too short to estimate."""
from __future__ import annotations

import numpy as np

_ANN = np.sqrt(252.0)


def _sharpe(x: np.ndarray) -> float:
    x = x[np.isfinite(x)]
    if len(x) < 2 or x.std() == 0:
        return float("nan")
    return float(x.mean() / x.std() * _ANN)


def marginal_sharpe(book: np.ndarray, sleeve: np.ndarray, *, weight: float = 0.2) -> float:
    n = min(len(book), len(sleeve))
    if n < 2:
        return float("nan")
    b, s = book[-n:], sleeve[-n:]
    base = _sharpe(b)
    blended = _sharpe((1.0 - weight) * b + weight * s)
    if not (np.isfinite(base) and np.isfinite(blended)):
        return float("nan")
    return blended - base
