"""Bounded R2 Fock halves on the accepted finite BIPOLE four-band fixture.

Stanton et al., Sec. II Eqs. (2)-(5),(9)-(10),(12)-(13), doi:10.1063/1.460620;
Riplinger and Neese, Sec. II D Eqs. (26)-(30), doi:10.1063/1.4773581. The source is the
spatial shared_residual_doubles in cpp/src/dlpno_ccsd.cpp. Its residual
includes diagonal Fock terms, unlike Stanton's right-hand-side convention.
"""
from contextlib import closing
from operator import index
from typing import NamedTuple
import numpy as np

from .bipole_terminal import (BipoleTransitions, _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 .source import CorrelationSourceError
from .translation import _readonly
from .translation_operators import matrix_record
from .translation_builder import _record

# Two sequential provider leases. Larger streamed consumer allowance covers
# two six-index-length outer products (2*6**4 complex entries per element).
STREAM_WORK = PASS_WORK + 6912*(131072-65536)
WORK_BOUND = PASS_WORK + STREAM_WORK


class FockTerms(NamedTuple):
    """Raw native halves and assembled ij + ji.T, in seven target frames."""
    ij: tuple
    ji: tuple
    total: tuple

    def placed(self, spaces, i, j):
        p=spaces.resolve(i,j)
        a,b,total=(leg[p.row] for leg in self)
        # Raw halves exchange WITHOUT a transpose. Only their assembled sum
        # transposes. For diagonal pairs, ji is the same half evaluated once.
        return (b,a,total.T) if p.transposed else (a,b,total)


def _intermediates(foo, fov, fvv, ovov, ooov, ovvv, t, d):
    """Complete virtual/occupied Fh blocks; d[m,a], t[m,n,a,b].

    The two 1/2 singles corrections combine with taut=T+.5*dd to
    yield tau=T+dd here. All six occupied indices are summed, including
    diagonals once, with spatial direct/exchange coefficients 2 and -1.
    """
    tau=t+np.einsum('ma,nb->mnab',d,d)
    fv=fvv-np.einsum('ma,me->ae',d,fov)
    fv+=2*np.einsum('mf,mfae->ae',d,ovvv)-np.einsum('mf,meaf->ae',d,ovvv)
    fv-=2*np.einsum('mnaf,menf->ae',tau,ovov)
    fv+=np.einsum('mnaf,mfne->ae',tau,ovov)
    fo=foo+fov@d.T
    fo+=2*np.einsum('ne,mxne->mx',d,ooov)-np.einsum('ne,nxme->mx',d,ooov)
    fo+=2*np.einsum('xnef,menf->mx',tau,ovov)-np.einsum('xnef,mfne->mx',tau,ovov)
    return fo,fv


def _real(a):
    if not np.isfinite(a).all() or np.max(abs(a.imag))>1e-12:
        raise CorrelationSourceError('BIPOLE Fock blocks failed real-frame time reversal')
    return a.real.copy()


def fock_terms(result, prepared, doubles, singles, *, max_bytes, max_work):
    """Return half_ij_fock, half_ji_fock and their source-defined sum.

    Reuse authenticated ovov provider blocks. Stream ooov/ovvv from the
    same signed terminal reader. This constructs orbital blocks, never a
    dense AO ERI or a positive auxiliary Gram. F comes from terminal F/S,
    not orbital-energy substitution. No ring or R1 contribution is included.
    """
    h=getattr(result,'terminal_transitions',None)
    if type(h) is not BipoleTransitions:
        raise CorrelationSourceError('BIPOLE Fock 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 Fock requires {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')
    if (not isinstance(doubles,(list,tuple)) or len(doubles)!=7 or any(
        not isinstance(t,np.ndarray) or t.shape!=(n,n)
        for t,n in zip(doubles,z.pair_ranks,strict=True))):
        raise ValueError('BIPOLE Fock requires one square doubles matrix per pair')
    ts=z.validate_tensors(doubles,name='Fock doubles')
    t1=tuple(_readonly(t) for t in singles)
    source=translation_source(result,_MESH,h,max_bytes)
    s,f=source.overlap,source.reference.fock
    if (z._fock.shape!=f.shape
        or matrix_record(f)!=_record(prepared.pair_build.provenance['fock'])
        or matrix_record(z._fock)!=_record(prepared.pair_build.provenance['fock'])):
        raise CorrelationSourceError('BIPOLE Fock frame differs from bound pair build')
    v=source.reference.mo_coeffs[:,6:]
    o=np.asarray(z._occupied)
    # Source T2 is lifted from each of its own frames; full diagonal singles
    # remain complete. Project onto a target only after forming intermediates.
    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:]
    ovov=np.zeros((6,)*4,complex)
    for p,q,r,k in blocks.momenta:
        ovov+=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)
    ovov=_real(ovov)
    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); 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])
            ovvv+=value*np.einsum('m,f,a,e->mfae',ob[p,u].conj(),vb[q,w],vb[r,x].conj(),vb[k,y])
    fo,fv=_intermediates(o.T@f@o,o.T@f@v,v.T@f@v,ovov,_real(ooov),_real(ovvv),t,d)
    a,b=[],[]
    for row,(i,j) in enumerate(z.representative_pairs):
        u=rotations[i,j]; fp=u.T@fv@u
        left=ts[row]@fp.T; right=ts[row].T@fp.T
        for m in range(6):
            for x,y,acc in ((i,j,left),(j,i,right)):
                overlap=z.overlap_between((i,j),(x,m))
                acc-=fo[m,y]*(overlap@z.orient_tensor(x,m,ts)@overlap.T)
        a.append(_readonly(left)); b.append(_readonly(right))
    h._validate(result,max_bytes); _bound_spaces(h,prepared)
    total=z.validate_tensors([x+y.T for x,y in zip(a,b,strict=True)],name='Fock sum')
    return FockTerms(tuple(a),tuple(b),total)


def resource_census():
    """Conservative simultaneous numerical storage within the transform slot."""
    from .bipole_terminal import _RESERVED,_DOMAIN,_PANEL
    arrays=dict(orbital_blocks_copies_scratch=16*6**4*16,
        band_provider_and_transform=16*(3*27+4)*16,
        source_adapter_frames_fock_metric=32*12*12*16,
        pair_rotations_amplitudes=4*6**4*8,
        fock_blocks_and_projected_scratch=32*6*6*8,
        retained_ladder_outputs_and_copies=96*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=131072,live_target_projected_pair_matrices=1,lifted_source_pair_matrices=36,
        occupied_count=6,ordered_occupied_pairs=36,representatives=7,
        assembly_work=assembly_work_bound(),assembly_leases=10)


def assembly_work_bound():
    from .bipole_terminal import BipoleTransitions
    from .bipole_virtual_singles import WORK_BOUND as linear
    from .bipole_virtual_disconnected import WORK_BOUND as disconnected
    from .bipole_virtual_cubic import WORK_BOUND as cubic
    return 4*PASS_WORK+BipoleTransitions.ladder_work_bound+linear+disconnected+cubic+WORK_BOUND


def ladders_fock_assembly(result, prepared, doubles, singles, *, max_bytes, max_work):
    """Bare seed + complete occupied/virtual ladders + the two Fock halves.

    This is a partial R2, not a complete residual. Rings and the later
    singles/integral half updates are excluded. Each ladder owns one half
    tau*(Z+Z1): reuse its array, adding it once to EACH ladder as the native
    source requires. Do not add occupied.t1_free (it contains half.tt again).
    """
    from .bipole_ccsd import _handle, complete_occupied_ladder
    from .bipole_virtual_singles import linear_virtual_ladder_terms, WORK_BOUND as linear_work
    from .bipole_virtual_disconnected import disconnected_virtual_ladder, WORK_BOUND as disc_work
    from .bipole_virtual_cubic import cubic_virtual_ladder, WORK_BOUND as cubic_work
    from .translation_builder import _array_record
    h=_handle(result); h._validate(result,max_bytes)
    work=assembly_work_bound()
    if isinstance(max_work,(bool,np.bool_)) or index(max_work)<work:
        raise ValueError(f'BIPOLE ladder/Fock assembly requires {work} work units')
    z=_bound_spaces(h,prepared)
    if (not isinstance(prepared.pair_build.integrals,(list,tuple))
        or len(prepared.pair_build.integrals)!=7 or any(
        not isinstance(t,np.ndarray) or t.shape!=(n,n)
        for t,n in zip(prepared.pair_build.integrals,z.pair_ranks,strict=True))):
        raise CorrelationSourceError('BIPOLE bare seed shape differs from bound pair build')
    if [_array_record(a) for a in prepared.pair_build.integrals]!=_record(prepared.pair_build.provenance['integrals']):
        raise CorrelationSourceError('BIPOLE bare seed differs from bound pair build')
    seed=z.validate_tensors(prepared.pair_build.integrals,name='bare R2 seed')
    fock=fock_terms(result,prepared,doubles,singles,max_bytes=max_bytes,max_work=WORK_BOUND)
    occupied=complete_occupied_ladder(result,prepared,doubles,singles,max_bytes=max_bytes,max_work=4*PASS_WORK)
    vv=h.bare_virtual_ladder(result,prepared,doubles,max_bytes=max_bytes,max_work=h.ladder_work_bound)
    linear=linear_virtual_ladder_terms(result,prepared,doubles,singles,max_bytes=max_bytes,max_work=linear_work)
    disc=disconnected_virtual_ladder(result,prepared,singles,max_bytes=max_bytes,max_work=disc_work)
    cubic=cubic_virtual_ladder(result,prepared,singles,max_bytes=max_bytes,max_work=cubic_work)
    six=tuple(a+b+c+d for a,b,c,d in zip(vv,linear.total,disc,cubic.total,strict=True))
    virtual=z.validate_tensors([a+b for a,b in zip(six,occupied['half'].total,strict=True)],name='complete virtual ladder')
    total=z.validate_tensors([a+b+c+d for a,b,c,d in zip(seed,occupied['total'],virtual,fock.total,strict=True)],
                            name='bare plus ladders plus Fock partial R2')
    h._validate(result,max_bytes); _bound_spaces(h,prepared)
    return dict(seed=seed,occupied=occupied,virtual_bare=vv,virtual_linear=linear,
        virtual_disconnected=disc,virtual_cubic=cubic,virtual_six=six,virtual=virtual,
        fock=fock,total=total,coverage='bare + occupied_ladder + virtual_ladder increments + ij/ji Fock halves',
        required_work=work,leases=10)
