"""Build a Book from research runs — turns the survivor library into an executable multi-strategy book.
Equal-weight the survivors up to the gross-leverage budget; the netting handles same-market overlap."""
from __future__ import annotations

from collections.abc import Iterable

from fxhnt.domain.models import ResearchRun
from fxhnt.domain.portfolio.models import Book, StrategyAllocation


def book_from_runs(runs: Iterable[ResearchRun], name: str, *,
                   max_gross_leverage: float = 1.0, passed_only: bool = True) -> Book:
    selected = [r for r in runs if (r.verdict.passed or not passed_only)]
    if not selected:
        raise ValueError("no qualifying runs to build a book from")
    weight = max_gross_leverage / len(selected)
    allocations = [StrategyAllocation(spec=r.spec, market=r.market, weight=weight) for r in selected]
    return Book(name=name, allocations=allocations, max_gross_leverage=max_gross_leverage)
