import numpy as np
from scipy.stats import spearmanr, ks_2samp

LH = np.array([10, 20, 40, 60, 120])
W = np.diff(np.r_[0, LH]) / 10


def expected_shortfall(losses, alpha=0.975):
    x = np.asarray(losses, dtype=float)
    if x.ndim != 1 or x.size == 0 or not np.isfinite(x).all():
        raise ValueError('Invalid scenario losses')
    if not 0 < alpha < 1:
        raise ValueError('Invalid confidence level')
    x = np.sort(x)[::-1]
    h = (1 - alpha) * len(x)
    k = int(np.floor(h))
    fraction = h - k
    tail_sum = x[:k].sum()
    if fraction > 0 and k < len(x):
        tail_sum += fraction * x[k]
    return float(tail_sum / h)


def liquidity_adjusted_es(subset_es):
    e = np.asarray(subset_es, dtype=float)
    if e.shape != (5,) or not np.isfinite(e).all():
        raise ValueError('Five valid nested-subset ES inputs required')
    return float(np.sqrt(np.dot(W, e**2)))


def stressed_charge(full_current, reduced_current, reduced_stress):
    f, r, s = map(float, (full_current, reduced_current, reduced_stress))
    if not np.isfinite([f, r, s]).all() or min(f, r, s) < 0:
        raise ValueError('Invalid liquidity-adjusted ES inputs')
    if r == 0:
        if f == 0 and s == 0:
            return 0.0  # only for a verified empty scope in this example
        raise ValueError('Degenerate reduced ES: approved policy required')
    return s * max(1.0, f / r)


def imcc(diversified, constrained):
    return 0.5 * stressed_charge(*diversified) + 0.5 * sum(
        stressed_charge(*triple) for triple in constrained
    )


def ses(credit_idio, equity_idio, other):
    a, b, c = (np.asarray(v, dtype=float) for v in
               (credit_idio, equity_idio, other))
    if any(v.ndim != 1 or not np.isfinite(v).all() or np.any(v < 0)
           for v in (a, b, c)):
        raise ValueError('Invalid NMRF charges')
    rho = 0.6
    return float(np.linalg.norm(a) + np.linalg.norm(b) +
                 np.sqrt((rho * c.sum())**2 + (1-rho**2)*np.dot(c, c)))


def backtesting_exceptions(apl, hpl, var):
    a, h, v = (np.asarray(x, dtype=float) for x in (apl, hpl, var))
    if a.shape != (250,) or a.shape != h.shape or h.shape != v.shape:
        raise ValueError('Aligned 250-day backtesting sample required')
    if np.any(v[np.isfinite(v)] < 0):
        raise ValueError('Expected nonnegative VaR loss threshold')
    bad_a = (~np.isfinite(a)) | (~np.isfinite(v)) | (-a > v)
    bad_h = (~np.isfinite(h)) | (~np.isfinite(v)) | (-h > v)
    na, nh = int(bad_a.sum()), int(bad_h.sum())
    return na, nh, max(na, nh)


def backtesting_multiplier(n, qualitative_addon=0.0):
    if not isinstance(n, (int, np.integer)) or not 0 <= n <= 250:
        raise ValueError('Invalid number of exceptions')
    if not np.isfinite(qualitative_addon) or qualitative_addon < 0:
        raise ValueError('Invalid qualitative add-on')
    schedule = {5: 1.70, 6: 1.76, 7: 1.83, 8: 1.88, 9: 1.92}
    base = 1.5 if n <= 4 else schedule.get(n, 2.0)
    return base + qualitative_addon


def pla(hpl, rtpl):
    h, r = np.asarray(hpl, float), np.asarray(rtpl, float)
    if h.shape != (250,) or r.shape != h.shape:
        raise ValueError('Aligned 250-day PLA sample required')
    if not np.isfinite(h).all() or not np.isfinite(r).all():
        raise ValueError('Invalid PLA observations: escalate')
    rho = float(spearmanr(h, r).statistic)
    ks = float(ks_2samp(h, r).statistic)
    if not np.isfinite(rho):
        raise ValueError('Undefined rank correlation: escalate')
    if rho > 0.80 and ks < 0.09:
        zone = 'green'
    elif rho < 0.70 or ks > 0.12:
        zone = 'red'
    else:
        zone = 'amber'
    return rho, ks, zone


def default_charge(latest, previous_12):
    previous = np.asarray(previous_12, float)
    if (previous.shape != (12,) or not np.isfinite(previous).all()
            or np.any(previous < 0) or not np.isfinite(latest) or latest < 0):
        raise ValueError('Valid latest and 12 weekly DRC values required')
    return max(float(latest), float(previous.mean()))


def final_capital(imcc_latest, ses_latest, imcc_history, ses_history,
                  mc, drc, sa_u, sa_eligible, sa_all,
                  sa_amber_standalone, sa_eligible_standalone):
    ih, sh = np.asarray(imcc_history, float), np.asarray(ses_history, float)
    if ih.shape != (60,) or sh.shape != (60,):
        raise ValueError('Expected 60-day history')
    scalar = np.array([imcc_latest, ses_latest, mc, drc, sa_u,
                       sa_eligible, sa_all, sa_amber_standalone,
                       sa_eligible_standalone], float)
    if (not np.isfinite(scalar).all() or np.any(scalar < 0)
            or not np.isfinite(ih).all() or not np.isfinite(sh).all()
            or np.any(ih < 0) or np.any(sh < 0) or mc < 1.5
            or sa_amber_standalone > sa_eligible_standalone):
        raise ValueError('Invalid capital input')
    ca = max(imcc_latest + ses_latest, mc * ih.mean() + sh.mean())
    ima = ca + drc
    k = 0.0 if sa_amber_standalone == 0 else (
        0.5 * sa_amber_standalone / sa_eligible_standalone)
    surcharge = k * max(0.0, sa_eligible - ima)
    acr = min(ima + surcharge + sa_u, sa_all) + max(0.0, ima-sa_eligible)
    return {'CA': ca, 'IMA_GA': ima, 'PLA_surcharge': surcharge,
            'capital': acr, 'RWA': 12.5 * acr}


full = liquidity_adjusted_es([10, 8, 5, 3, 1])
headline_imcc = imcc((full, 12, 20), [
    (10, 8, 14), (8, 6, 11), (3, 3, 5), (5, 4, 7), (7, 6, 10)
])
headline_ses = ses([3, 4], [2], [5, 5])
result = final_capital(
    headline_imcc, headline_ses, np.full(60, 40.0), np.full(60, 14.0),
    backtesting_multiplier(5), default_charge(8, np.full(12, 7.0)),
    12, 110, 118, 30, 120
)
assert np.isclose(result['capital'], 104.5)
assert np.isclose(result['RWA'], 1306.25)
assert np.isclose(liquidity_adjusted_es([2, 2, 2, 2, 2]), 2*np.sqrt(12))
assert np.isclose(stressed_charge(8, 10, 12), 12)
print(result)
