"""Finite BIPOLE R1: doubles_fme minus occupied_fock at fixed amplitudes.

Stanton et al., Sec. II Eqs. (1),(5), doi:10.1063/1.460620 (spin orbitals);
Riplinger and Neese, Sec. II D Eq. (30), doi:10.1063/1.4773581 (pair metric).
"""
import numpy as np

from .bipole_ccsd import _check_blocks
from .bipole_fock import PASS_WORK, _real
from .bipole_r1_fock import _source
from .bipole_terminal import _characters, _MESH, _OUTPUT, _RESERVED
from .bipole_virtual_singles import _bound_spaces
from .source import CorrelationSourceError
from .translation import _readonly

# One authenticated ovov pass; reserve separate work for the 27 small
# sequential four-leg orbital transforms and the 36 source pair contractions.
WORK_BOUND = PASS_WORK + 2**24
PIECES = ('bare_fov', 'direct', 'exchange')


def _placed_ovov(h, blocks, s, o, v):
    band = blocks.blocks['ovov']
    if (band.shape != (3,3,3,2,2,2,2) or band.dtype != np.complex128
            or not np.isfinite(band).all()):
        raise CorrelationSourceError('invalid finite ovov block')
    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', band[p,q,r],
                       ro[p].conj(), rv[q], ro[r].conj(), rv[k], optimize=True)
    return _real(g)


def _contract(fov, ovov, rotations, doubles, singles):
    """Full six-member diagonal neighborhoods, for the unscreened fixture only."""
    d = np.stack([rotations[n,n] @ singles[n % 2] for n in range(6)])
    rows = (fov, 2*np.einsum('menf,nf->me', ovov, d),
            -np.einsum('mfne,nf->me', ovov, d))
    out = {name: [] for name in (*PIECES, 'increment')}
    for i in range(6):
        target = rotations[i,i]
        pieces = np.zeros((3, target.shape[1]))
        for m in range(6):
            u, t = rotations[i,m], doubles[i,m]
            # Resolve T(i,m) *before* spin adaptation. U.T puts the e leg
            # in [im]; the mixed metric acts only on the remaining a leg.
            fme = np.stack([row[m] @ u for row in rows], axis=1)
            local = (2*t - t.T) @ fme
            pieces += ((target.T @ u) @ local).T
        for name, value in zip(PIECES, pieces, strict=True):
            out[name].append(_readonly(value))
        out['increment'].append(_readonly(pieces.sum(axis=0)))
    return {name: tuple(values) for name, values in out.items()}


def doubles_fme_terms(result, prepared, doubles, singles, *, max_bytes, max_work):
    """Three signed terms and their sum, in each of the six diagonal frames."""
    h, z, source = _source(result, prepared, max_bytes, max_work, WORK_BOUND)
    if (not isinstance(singles, (tuple, list)) or len(singles) != 2 or any(
            not isinstance(a, np.ndarray) or a.shape != (z.pair_ranks[z.resolve(n,n).row],)
            or a.dtype.kind not in 'iuf' or not np.isfinite(a).all() for n,a in enumerate(singles))):
        raise ValueError('BIPOLE singles require two finite real diagonal PNO vectors')
    ts = z.validate_tensors(doubles, name='R1 doubles-Fme')
    t1 = tuple(_readonly(a) for a in singles)
    s, v, o = source.overlap, source.reference.mo_coeffs[:,6:], z._occupied
    rotations = {(i,m): v.T @ s @ z.coefficients(i,m) for i in range(6) for m in range(6)}
    oriented = {ij: z.orient_tensor(*ij, ts) for ij in rotations}
    blocks = h.coulomb_blocks(('ovov',), mesh=_MESH, max_bytes=max_bytes, max_work=PASS_WORK)
    _check_blocks(blocks, h, result, _MESH, ('ovov',))
    ovov = _placed_ovov(h, blocks, s, o, v)
    out = _contract(o.T @ source.reference.fock @ v, ovov, rotations, oriented, t1)
    h._validate(result, max_bytes)
    _bound_spaces(h, prepared)
    return out


def resource_census():
    """Concurrent numerical arrays beyond the terminal domain and panel slots."""
    arrays = dict(band_blocks_and_scratch=16*(3*27+4)*16,
                  transformed_ovov_and_einsum_scratch=8*6**4*16,
                  source_frames_and_fock=32*12*12*16,
                  rotations_amplitudes_rows_and_outputs=12*36*6*3*8)
    assert sum(arrays.values()) <= _OUTPUT
    return dict(arrays=arrays, numerical_bytes_upper_bound=sum(arrays.values()),
                required_bytes=_RESERVED, required_work=WORK_BOUND, provider_work=PASS_WORK,
                leases=1, domains=256, normalized_elements=6912, momentum_blocks=27,
                ordered_pairs=36, targets=6)
