"""Combine sleeve return streams into a book's return timeseries — date-aligned weighted sum.
Pure: the historical analogue of compute_target_weights (which acts on the latest bar for live execution)."""
from __future__ import annotations

import numpy as np

Sleeve = tuple[float, tuple[str, ...], np.ndarray]  # (weight, dates, returns)


def combine_returns(sleeves: list[Sleeve]) -> tuple[tuple[str, ...], np.ndarray]:
    """Align all sleeves on their COMMON dates (intersection) and return (dates, capital-weighted returns).
    Different markets have different calendars; the intersection is the honest common backtest window."""
    if not sleeves:
        return (), np.array([])
    common = set(sleeves[0][1])
    for _, dates, _ in sleeves[1:]:
        common &= set(dates)
    common_dates = tuple(sorted(common))
    if not common_dates:
        return (), np.array([])
    out = np.zeros(len(common_dates))
    for weight, dates, returns in sleeves:
        index = {d: i for i, d in enumerate(dates)}
        out += weight * np.array([returns[index[d]] for d in common_dates])
    return common_dates, out
