"""Isolated finite BIPOLE R1 singles_integrals minus doubles_fme.

Stanton et al., Sec. II Eq. (1), doi:10.1063/1.460620; diagonal pair
frames as in Riplinger and Neese, Sec. II D, doi:10.1063/1.4773581.
"""
from contextlib import closing
from operator import index

import numpy as np

from .bipole_fock import _real
from .bipole_terminal import (
    BipoleTransitions, _characters, _DOMAIN, _FOUR_BAND_PANEL_WORK, _LADDER_DOMAIN_WORK,
    _LADDER_SETUP_WORK, _OUTPUT, _PANEL, _RESERVED, block_momenta,
)
from .bipole_virtual_singles import _bound_spaces
from .source import CorrelationSourceError
from .translation import _readonly

# One pass with two 6 x 6 x 2 x 2 complex outer products per element.
_CONSUMER_WORK = 65536
WORK_BOUND = _LADDER_SETUP_WORK + 256 * (
    _LADDER_DOMAIN_WORK + 27 * (_FOUR_BAND_PANEL_WORK + _CONSUMER_WORK))
_FULL = (tuple(range(6)),) * 6


def _mixed_tiles(h, z):
    """Tiles indexed n,i,a[ ii ],f[ nn ]; conjugate Bloch legs 1 and 3."""
    inverse = _characters().conj().T
    o = np.einsum('kt,tun->kun', inverse, z._occupied.reshape(3,4,6))
    frames = np.stack([z.coefficients(n,n) for n in range(6)], axis=1).reshape(3,4,6,2)
    c = np.einsum('kt,tunf->kunf', inverse, frames)
    j = np.zeros((6,6,2,2), complex)
    k = np.zeros_like(j)
    momenta = block_momenta(h._owner.declaration.mesh)
    with closing(h._elements(momenta, _LADDER_DOMAIN_WORK)) as elements:
        for (u,v,x,y), (p,q,r,s), value in elements:
            j += value * np.einsum('n,nf,i,ia->niaf', o[p,u].conj(), c[q,v],
                                   o[r,x].conj(), c[s,y])
            k += value * np.einsum('n,i,ia,nf->niaf', o[p,u].conj(), o[q,v],
                                   c[r,x].conj(), c[s,y])
    return _real(j), _real(k)


def _contract(tiles, singles, neighborhoods):
    """None marks a missing diagonal. An off-diagonal pair is never needed."""
    j, k = tiles
    out = {key: [] for key in ('direct', 'exchange', 'increment')}
    for i, neighbors in enumerate(neighborhoods):
        if singles[i] is None:
            for values in out.values():
                values.append(None)
            continue
        direct = np.zeros_like(singles[i], dtype=float)
        exchange = np.zeros_like(direct)
        for n in neighbors:
            t = singles[n]
            if t is not None:
                direct += 2 * (j[n,i] @ t)
                exchange -= k[n,i] @ t
        for key, value in zip(out, (direct, exchange, direct + exchange), strict=True):
            out[key].append(_readonly(value))
    return {k: tuple(v) for k,v in out.items()}


def singles_integral_terms(result, prepared, singles, *, max_bytes, max_work):
    """Return the signed direct, exchange and increment in each target [ii].

    Only the accepted unscreened four-band pair build is admitted. T2 is
    not an operand. Each home T1 is carried unchanged to its two images.
    """
    h = getattr(result, 'terminal_transitions', None)
    if type(h) is not BipoleTransitions:
        raise CorrelationSourceError('BIPOLE R1 requires a result-owned terminal handle')
    h._validate(result, max_bytes)
    if isinstance(max_work, (bool, np.bool_)) or index(max_work) < WORK_BOUND:
        raise ValueError(f'BIPOLE R1 singles integrals require {WORK_BOUND} work units')
    z = _bound_spaces(h, prepared)
    if (not isinstance(singles, (list, tuple)) or len(singles) != 2 or any(
            not isinstance(t, np.ndarray) or t.shape != (z.pair_ranks[z.resolve(i,i).row],)
            or t.dtype.kind not in 'iuf' or not np.isfinite(t).all() for i,t in enumerate(singles))):
        raise ValueError('BIPOLE singles require two finite real diagonal PNO vectors')
    t1 = tuple(_readonly(t) for t in singles) * 3
    terms = _contract(_mixed_tiles(h, z), t1, _FULL)
    h._validate(result, max_bytes)
    _bound_spaces(h, prepared)
    return terms


def resource_census():
    """Conservative numerical byte bounds, including both complex tile accumulators."""
    arrays = dict(validation_copies=32*12*12*16,
                  placed_frames_fourier_projections_and_conjugates=12*12*12*16,
                  both_tiles_products_and_real_reconstruction=8*6*6*2*2*16,
                  singles_accumulators_outputs_and_copies=12*6*2*8)
    assert sum(arrays.values()) <= _OUTPUT
    return dict(arrays=arrays, numerical_bytes_upper_bound=sum(arrays.values()),
                domain_bytes=_DOMAIN, panel_bytes=_PANEL, output_slot_bytes=_OUTPUT,
                required_bytes=_RESERVED, required_work=WORK_BOUND, setup_work=_LADDER_SETUP_WORK,
                work_per_domain=_LADDER_DOMAIN_WORK, native_work_per_element=_FOUR_BAND_PANEL_WORK,
                consumer_work_per_element=_CONSUMER_WORK, leases=1, domains=256,
                momentum_quartets=27, normalized_elements=6912, mixed_tile_shape=(6,6,2,2))
