"""Diversification gate — the selection that makes the factory about UNCORRELATED edges. Admit a
forward-survivor to the deployed book only if (a) its LEFT-TAIL correlation to the book is below the cap and
(b) it adds at least `min_marginal` to book Sharpe. Fail-safe: an unestimable tail correlation is NOT
admitted (don't deploy on unknown crisis-correlation)."""
from __future__ import annotations

from dataclasses import dataclass

import numpy as np

from fxhnt.domain.diversification.correlation import left_tail_correlation
from fxhnt.domain.diversification.marginal import marginal_sharpe


@dataclass(frozen=True, slots=True)
class DiversificationVerdict:
    admit: bool
    left_tail_corr: float
    marginal: float
    reason: str


def diversification_gate(sleeve: np.ndarray, book: np.ndarray, *, max_tail_corr: float,
                         min_marginal: float, tail_frac: float, weight: float = 0.2) -> DiversificationVerdict:
    lt = left_tail_correlation(sleeve, book, tail_frac=tail_frac)
    mg = marginal_sharpe(book, sleeve, weight=weight)
    if not np.isfinite(lt):
        return DiversificationVerdict(False, lt, mg, "left-tail correlation unestimable — fail-safe reject")
    if lt >= max_tail_corr:
        return DiversificationVerdict(False, lt, mg, f"left-tail corr {lt:.2f} ≥ {max_tail_corr}")
    if not np.isfinite(mg):
        return DiversificationVerdict(False, lt, mg, "marginal Sharpe unestimable — fail-safe reject")
    if mg < min_marginal:
        return DiversificationVerdict(False, lt, mg, f"marginal Sharpe {mg:.3f} < {min_marginal}")
    return DiversificationVerdict(True, lt, mg, f"admit: tail-corr {lt:.2f}, +{mg:.3f} Sharpe")
