"""Correlation between return streams — full-sample and LEFT-TAIL. The left tail (the book's worst days) is
the crisis-relevant measure: correlations spike in selloffs, so a sleeve uncorrelated full-sample but
co-moving in the tail must be caught. Returns NaN when there are too few aligned/tail days to estimate."""
from __future__ import annotations

import numpy as np

_MIN_TAIL_DAYS = 3


def _aligned(a: np.ndarray, b: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
    if len(a) == 0 or len(b) == 0:
        return np.array([]), np.array([])
    n = min(len(a), len(b))
    a, b = a[-n:], b[-n:]
    m = np.isfinite(a) & np.isfinite(b)
    return a[m], b[m]


def full_correlation(a: np.ndarray, b: np.ndarray) -> float:
    a, b = _aligned(a, b)
    if len(a) < 2 or a.std() < 1e-12 or b.std() < 1e-12:
        return float("nan")
    return float(np.corrcoef(a, b)[0, 1])


def left_tail_correlation(sleeve: np.ndarray, book: np.ndarray, *, tail_frac: float = 0.10) -> float:
    """Correlation of sleeve vs book on the days the BOOK is in its worst `tail_frac` quantile."""
    s, b = _aligned(sleeve, book)
    k = int(len(b) * tail_frac)
    if k < _MIN_TAIL_DAYS:
        return float("nan")
    worst = np.argsort(b)[:k]                      # indices of the book's lowest returns
    sv, bv = s[worst], b[worst]
    if sv.std() < 1e-12 or bv.std() < 1e-12:
        return float("nan")
    return float(np.corrcoef(sv, bv)[0, 1])
