"""Finite BIPOLE R2 ring increments, excluding the later half updates.

Stanton et al., Sec. II Eqs. (2),(8)-(10), doi:10.1063/1.460620;
Riplinger/Neese, Sec. II C-D Eqs. (26)-(30), doi:10.1063/1.4773581.
Spatial coefficients and boundaries follow shared_residual_doubles in
cpp/src/dlpno_ccsd.cpp. No positive factorization of the operator is used.
"""
from contextlib import closing
from operator import index
import numpy as np

from .bipole_terminal import _characters, _MESH, _LADDER_DOMAIN_WORK, translation_source
from .bipole_ccsd import _check_blocks
from .bipole_virtual_half import WORK_BOUND as PASS_WORK
from .bipole_virtual_singles import _bound_spaces
from .bipole_fock import FockTerms, _real
from .translation import _readonly

# One authenticated ovov lease and one stream of ooov/oovv/ovvv. The
# consumer allowance covers three complex 6**4 outer products per element.
STREAM_WORK = PASS_WORK + 6912*(196608-65536)
WORK_BOUND = PASS_WORK + STREAM_WORK


def _intermediates(m, x, g, h, k, l, t, d):
    """W1/W2/WX for one occupied neighborhood, complete virtual coordinates.

    g=(me|nf), h=(mx|ne), k=(mx|be), l=(me|bf). Both t[n,x]
    and t[x,n] are retained; amplitudes are not conjugated. Projection of
    the free e,b legs into different source/target frames happens later.
    """
    direct = g[m, :, x, :] + np.einsum('ebf,f->eb', l[m], d[x])
    exchange = k[m, x].T + np.einsum('fbe,f->eb', l[m], d[x])
    w1 = direct - np.einsum('ne,nb->eb', h[:, x, m, :], d)
    wx = -exchange + np.einsum('ne,nb->eb', h[m, x], d)
    w2 = w1 + wx
    for n in range(len(d)):
        c, ex = g[m, :, n, :], g[n, :, m, :]
        ss = np.outer(d[x], d[n])
        common = c @ (t[n, x] - .5*t[x, n] - ss)
        w1 += common - .5*ex @ t[n, x]
        w2 += common + ex @ (.5*(t[x, n]-t[n, x]) + ss)
        wx += ex @ (.5*t[x, n] + ss)
    return w1, w2, wx


def ring_terms(result, prepared, doubles, singles, *, max_bytes, max_work):
    """Return isolated ij, ji and ij + ji.T ring increments.

    This action is deliberately limited to the accepted finite four-band
    source and seven unequal pair frames. Each occupied sum is complete.
    It does not include half_ij - half_ij_ring or any R1 contribution.
    """
    h = result.terminal_transitions
    h._validate(result, max_bytes)
    if isinstance(max_work, (bool, np.bool_)) or index(max_work) < WORK_BOUND:
        raise ValueError(f'BIPOLE ring requires {WORK_BOUND} work units')
    z = _bound_spaces(h, prepared)
    if (not isinstance(singles, (list, tuple)) or len(singles) != 2 or any(
        not isinstance(a, np.ndarray) or a.shape != (z.pair_ranks[z.resolve(i,i).row],)
        or a.dtype.kind not in 'iuf' or not np.isfinite(a).all()
        for i,a in enumerate(singles))):
        raise ValueError('BIPOLE singles require two finite real diagonal PNO vectors')
    if (not isinstance(doubles, (list, tuple)) or len(doubles) != 7 or any(
        not isinstance(a, np.ndarray) or a.shape != (n,n)
        for a,n in zip(doubles, z.pair_ranks, strict=True))):
        raise ValueError('BIPOLE ring requires one square doubles matrix per pair')
    ts = z.validate_tensors(doubles, name='ring doubles')
    t1 = tuple(_readonly(a) for a in singles)
    source = translation_source(result, _MESH, h, max_bytes)
    s, v, o = source.overlap, source.reference.mo_coeffs[:,6:], np.asarray(z._occupied)
    rotations = {(m,n): v.T @ s @ z.coefficients(m,n) for m in range(6) for n in range(6)}
    t = np.empty((6,6,6,6))
    for (m,n), u in rotations.items():
        t[m,n] = u @ z.orient_tensor(m,n,ts) @ u.T
    d = np.stack([rotations[m,m] @ t1[m%2] for m in range(6)])
    blocks = h.coulomb_blocks(('ovov',), mesh=_MESH, max_bytes=max_bytes, max_work=PASS_WORK)
    _check_blocks(blocks, h, result, _MESH, ('ovov',))
    mo = np.einsum('tk,kub->tukb', _characters(), h.orbitals.coefficients).reshape(12,12)
    ro = (mo.conj().T @ s @ o).reshape(3,4,6)[:,:2]
    rv = (mo.conj().T @ s @ v).reshape(3,4,6)[:,2:]
    g = np.zeros((6,)*4, complex)
    for p,q,r,k in blocks.momenta:
        g += np.einsum('abcd,am,be,cn,df->menf', blocks.blocks['ovov'][p,q,r],
            ro[p].conj(), rv[q], ro[r].conj(), rv[k], optimize=True)
    g = _real(g)
    inverse = _characters().conj().T
    ob = np.einsum('kt,tur->kur', inverse, o.reshape(3,4,6))
    vb = np.einsum('kt,tur->kur', inverse, v.reshape(3,4,6))
    ooov = np.zeros((6,)*4, complex)
    oovv = np.zeros_like(ooov); ovvv = np.zeros_like(ooov)
    with closing(h._elements(blocks.momenta, _LADDER_DOMAIN_WORK)) as panels:
        for (u,w,x,y),(p,q,r,k),value in panels:
            ooov += value*np.einsum('m,i,n,e->mine', ob[p,u].conj(), ob[q,w], ob[r,x].conj(), vb[k,y])
            oovv += value*np.einsum('m,i,b,e->mibe', ob[p,u].conj(), ob[q,w], vb[r,x].conj(), vb[k,y])
            ovvv += value*np.einsum('m,e,b,f->mebf', ob[p,u].conj(), vb[q,w], vb[r,x].conj(), vb[k,y])
    ooov, oovv, ovvv = (_real(a) for a in (ooov, oovv, ovvv))
    terms = _contract(z, ts, rotations, t, d, g, ooov, oovv, ovvv)
    h._validate(result, max_bytes); _bound_spaces(h, prepared)
    return terms


def _contract(z, ts, rotations, t, d, g, ooov, oovv, ovvv):
    """Contract one mixed source/target neighborhood at a time."""
    halves = [[], []]
    for i,j in z.representative_pairs:
        target = rotations[i,j]
        for leg,(a,b) in enumerate(((i,j),(j,i))):
            acc = np.zeros((target.shape[1],)*2)
            for m in range(6):
                w1,w2,_ = _intermediates(m,b,g,ooov,oovv,ovvv,t,d)
                q = rotations[a,m]; overlap = target.T @ q
                amp = z.orient_tensor(a,m,ts)
                # Only the a leg is projected first; e stays in [a,m].
                acc += (overlap @ (amp-amp.T)) @ (q.T @ w1 @ target)
                acc += (overlap @ amp) @ (q.T @ w2 @ target)
                del w1,w2
                _,_,wx = _intermediates(m,a,g,ooov,oovv,ovvv,t,d)
                q = rotations[m,b]; overlap = target.T @ q
                acc += (overlap @ z.orient_tensor(m,b,ts)) @ (q.T @ wx @ target)
                del wx
            halves[leg].append(_readonly(acc))
    total = z.validate_tensors([a+b.T for a,b in zip(*halves, strict=True)], name='ring sum')
    return FockTerms(tuple(halves[0]), tuple(halves[1]), total)


def assembly_work_bound():
    from .bipole_fock import assembly_work_bound as earlier
    return earlier() + WORK_BOUND


def ladders_fock_ring_assembly(result, prepared, doubles, singles, *, max_bytes, max_work):
    """Add each ring once to the qualified bare/ladder/Fock assembly."""
    from .bipole_fock import ladders_fock_assembly, assembly_work_bound as earlier_work
    h = result.terminal_transitions
    h._validate(result, max_bytes)
    if isinstance(max_work, (bool, np.bool_)) or index(max_work) < assembly_work_bound():
        raise ValueError(f'BIPOLE ring assembly requires {assembly_work_bound()} work units')
    earlier = ladders_fock_assembly(result, prepared, doubles, singles,
        max_bytes=max_bytes, max_work=earlier_work())
    ring = ring_terms(result, prepared, doubles, singles, max_bytes=max_bytes, max_work=WORK_BOUND)
    z = _bound_spaces(h, prepared)
    total = z.validate_tensors([a+b for a,b in zip(earlier['total'], ring.total, strict=True)],
                              name='bare ladders Fock ring partial R2')
    return dict(earlier=earlier, ring=ring, total=total, leases=12,
        coverage='bare + complete occupied/virtual ladder increments + Fock halves + isolated ring halves',
        required_work=assembly_work_bound())


def resource_census():
    """Conservative simultaneous numerical peak, including retained inputs.

    All sizes are bounded by admission to the fixed 12-AO, 6-occupied,
    6-virtual fixture. Domain/panel reservations are additional. This is
    neither a process-RSS guarantee nor a general linear-scaling claim.
    """
    from .bipole_terminal import _RESERVED, _DOMAIN, _PANEL
    arrays = dict(integral_accumulators_copies_and_outer_scratch=24*6**4*16,
        authenticated_band_block_and_transform=16*(3*27+4)*16,
        adapter_frames_fock_metric_and_retained_inputs=32*12*12*16,
        oriented_source_doubles_rotations_and_singles=4*6**4*8,
        live_W1_W2_WX_and_dressing_scratch=48*6*6*8,
        projected_amplitudes_mixed_blocks_accumulators=32*3*3*8,
        retained_ladder_Fock_ring_outputs_and_copies=128*33*8)
    size = sum(arrays.values())
    assert size <= _RESERVED-_DOMAIN-_PANEL
    return dict(numerical_array_bounds=arrays, numerical_bytes_upper_bound=size,
        required_bytes=_RESERVED, required_work=WORK_BOUND, leases=2,
        domains_per_lease=256, normalized_elements_per_lease=6912,
        streamed_consumer_work_per_element=196608, occupied_count=6,
        ordered_source_pairs=36, live_occupied_neighborhoods=1,
        assembly_work=assembly_work_bound(), assembly_leases=12)
